babylon.max.js 3.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. var EffectFallbacks = /** @class */ (function () {
  20. function EffectFallbacks() {
  21. this._defines = {};
  22. this._currentRank = 32;
  23. this._maxRank = -1;
  24. }
  25. EffectFallbacks.prototype.unBindMesh = function () {
  26. this._mesh = null;
  27. };
  28. EffectFallbacks.prototype.addFallback = function (rank, define) {
  29. if (!this._defines[rank]) {
  30. if (rank < this._currentRank) {
  31. this._currentRank = rank;
  32. }
  33. if (rank > this._maxRank) {
  34. this._maxRank = rank;
  35. }
  36. this._defines[rank] = new Array();
  37. }
  38. this._defines[rank].push(define);
  39. };
  40. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  41. this._mesh = mesh;
  42. if (rank < this._currentRank) {
  43. this._currentRank = rank;
  44. }
  45. if (rank > this._maxRank) {
  46. this._maxRank = rank;
  47. }
  48. };
  49. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  50. get: function () {
  51. return this._currentRank <= this._maxRank;
  52. },
  53. enumerable: true,
  54. configurable: true
  55. });
  56. EffectFallbacks.prototype.reduce = function (currentDefines) {
  57. // First we try to switch to CPU skinning
  58. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  59. this._mesh.computeBonesUsingShaders = false;
  60. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  61. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  62. var scene = this._mesh.getScene();
  63. for (var index = 0; index < scene.meshes.length; index++) {
  64. var otherMesh = scene.meshes[index];
  65. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  66. otherMesh.computeBonesUsingShaders = false;
  67. }
  68. }
  69. }
  70. else {
  71. var currentFallbacks = this._defines[this._currentRank];
  72. if (currentFallbacks) {
  73. for (var index = 0; index < currentFallbacks.length; index++) {
  74. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  75. }
  76. }
  77. this._currentRank++;
  78. }
  79. return currentDefines;
  80. };
  81. return EffectFallbacks;
  82. }());
  83. BABYLON.EffectFallbacks = EffectFallbacks;
  84. var EffectCreationOptions = /** @class */ (function () {
  85. function EffectCreationOptions() {
  86. }
  87. return EffectCreationOptions;
  88. }());
  89. BABYLON.EffectCreationOptions = EffectCreationOptions;
  90. var Effect = /** @class */ (function () {
  91. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  92. if (samplers === void 0) { samplers = null; }
  93. if (defines === void 0) { defines = null; }
  94. if (fallbacks === void 0) { fallbacks = null; }
  95. if (onCompiled === void 0) { onCompiled = null; }
  96. if (onError === void 0) { onError = null; }
  97. var _this = this;
  98. this.uniqueId = 0;
  99. this.onCompileObservable = new BABYLON.Observable();
  100. this.onErrorObservable = new BABYLON.Observable();
  101. this.onBindObservable = new BABYLON.Observable();
  102. this._uniformBuffersNames = {};
  103. this._isReady = false;
  104. this._compilationError = "";
  105. this.name = baseName;
  106. if (attributesNamesOrOptions.attributes) {
  107. var options = attributesNamesOrOptions;
  108. this._engine = uniformsNamesOrEngine;
  109. this._attributesNames = options.attributes;
  110. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  111. this._samplers = options.samplers;
  112. this.defines = options.defines;
  113. this.onError = options.onError;
  114. this.onCompiled = options.onCompiled;
  115. this._fallbacks = options.fallbacks;
  116. this._indexParameters = options.indexParameters;
  117. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  118. if (options.uniformBuffersNames) {
  119. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  120. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  121. }
  122. }
  123. }
  124. else {
  125. this._engine = engine;
  126. this.defines = defines;
  127. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  128. this._samplers = samplers;
  129. this._attributesNames = attributesNamesOrOptions;
  130. this.onError = onError;
  131. this.onCompiled = onCompiled;
  132. this._indexParameters = indexParameters;
  133. this._fallbacks = fallbacks;
  134. }
  135. this.uniqueId = Effect._uniqueIdSeed++;
  136. var vertexSource;
  137. var fragmentSource;
  138. if (baseName.vertexElement) {
  139. vertexSource = document.getElementById(baseName.vertexElement);
  140. if (!vertexSource) {
  141. vertexSource = baseName.vertexElement;
  142. }
  143. }
  144. else {
  145. vertexSource = baseName.vertex || baseName;
  146. }
  147. if (baseName.fragmentElement) {
  148. fragmentSource = document.getElementById(baseName.fragmentElement);
  149. if (!fragmentSource) {
  150. fragmentSource = baseName.fragmentElement;
  151. }
  152. }
  153. else {
  154. fragmentSource = baseName.fragment || baseName;
  155. }
  156. this._loadVertexShader(vertexSource, function (vertexCode) {
  157. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  158. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  159. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  160. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  161. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  162. if (baseName) {
  163. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  164. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  165. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  166. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  167. }
  168. else {
  169. _this._vertexSourceCode = migratedVertexCode;
  170. _this._fragmentSourceCode = migratedFragmentCode;
  171. }
  172. _this._prepareEffect();
  173. });
  174. });
  175. });
  176. });
  177. });
  178. });
  179. }
  180. Object.defineProperty(Effect.prototype, "key", {
  181. get: function () {
  182. return this._key;
  183. },
  184. enumerable: true,
  185. configurable: true
  186. });
  187. // Properties
  188. Effect.prototype.isReady = function () {
  189. return this._isReady;
  190. };
  191. Effect.prototype.getEngine = function () {
  192. return this._engine;
  193. };
  194. Effect.prototype.getProgram = function () {
  195. return this._program;
  196. };
  197. Effect.prototype.getAttributesNames = function () {
  198. return this._attributesNames;
  199. };
  200. Effect.prototype.getAttributeLocation = function (index) {
  201. return this._attributes[index];
  202. };
  203. Effect.prototype.getAttributeLocationByName = function (name) {
  204. var index = this._attributesNames.indexOf(name);
  205. return this._attributes[index];
  206. };
  207. Effect.prototype.getAttributesCount = function () {
  208. return this._attributes.length;
  209. };
  210. Effect.prototype.getUniformIndex = function (uniformName) {
  211. return this._uniformsNames.indexOf(uniformName);
  212. };
  213. Effect.prototype.getUniform = function (uniformName) {
  214. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  215. };
  216. Effect.prototype.getSamplers = function () {
  217. return this._samplers;
  218. };
  219. Effect.prototype.getCompilationError = function () {
  220. return this._compilationError;
  221. };
  222. // Methods
  223. Effect.prototype.executeWhenCompiled = function (func) {
  224. if (this.isReady()) {
  225. func(this);
  226. return;
  227. }
  228. this.onCompileObservable.add(function (effect) {
  229. func(effect);
  230. });
  231. };
  232. Effect.prototype._loadVertexShader = function (vertex, callback) {
  233. if (BABYLON.Tools.IsWindowObjectExist()) {
  234. // DOM element ?
  235. if (vertex instanceof HTMLElement) {
  236. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  237. callback(vertexCode);
  238. return;
  239. }
  240. }
  241. // Base64 encoded ?
  242. if (vertex.substr(0, 7) === "base64:") {
  243. var vertexBinary = window.atob(vertex.substr(7));
  244. callback(vertexBinary);
  245. return;
  246. }
  247. // Is in local store ?
  248. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  249. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  250. return;
  251. }
  252. var vertexShaderUrl;
  253. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  254. vertexShaderUrl = vertex;
  255. }
  256. else {
  257. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  258. }
  259. // Vertex shader
  260. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  261. };
  262. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  263. if (BABYLON.Tools.IsWindowObjectExist()) {
  264. // DOM element ?
  265. if (fragment instanceof HTMLElement) {
  266. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  267. callback(fragmentCode);
  268. return;
  269. }
  270. }
  271. // Base64 encoded ?
  272. if (fragment.substr(0, 7) === "base64:") {
  273. var fragmentBinary = window.atob(fragment.substr(7));
  274. callback(fragmentBinary);
  275. return;
  276. }
  277. // Is in local store ?
  278. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  279. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  280. return;
  281. }
  282. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  283. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  284. return;
  285. }
  286. var fragmentShaderUrl;
  287. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  288. fragmentShaderUrl = fragment;
  289. }
  290. else {
  291. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  292. }
  293. // Fragment shader
  294. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  295. };
  296. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  297. // Rebuild shaders source code
  298. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  299. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  300. vertexCode = prefix + vertexCode;
  301. fragmentCode = prefix + fragmentCode;
  302. // Number lines of shaders source code
  303. var i = 2;
  304. var regex = /\n/gm;
  305. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  306. i = 2;
  307. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  308. // Dump shaders name and formatted source code
  309. if (this.name.vertexElement) {
  310. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  311. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  312. }
  313. else if (this.name.vertex) {
  314. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  315. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  316. }
  317. else {
  318. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  319. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  320. }
  321. };
  322. ;
  323. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  324. var preparedSourceCode = this._processPrecision(sourceCode);
  325. if (this._engine.webGLVersion == 1) {
  326. callback(preparedSourceCode);
  327. return;
  328. }
  329. // Already converted
  330. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  331. callback(preparedSourceCode.replace("#version 300 es", ""));
  332. return;
  333. }
  334. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  335. // Remove extensions
  336. // #extension GL_OES_standard_derivatives : enable
  337. // #extension GL_EXT_shader_texture_lod : enable
  338. // #extension GL_EXT_frag_depth : enable
  339. // #extension GL_EXT_draw_buffers : require
  340. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  341. var result = preparedSourceCode.replace(regex, "");
  342. // Migrate to GLSL v300
  343. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  344. result = result.replace(/attribute[ \t]/g, "in ");
  345. result = result.replace(/[ \t]attribute/g, " in");
  346. if (isFragment) {
  347. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  348. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  349. result = result.replace(/texture2D\s*\(/g, "texture(");
  350. result = result.replace(/textureCube\s*\(/g, "texture(");
  351. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  352. result = result.replace(/gl_FragColor/g, "glFragColor");
  353. result = result.replace(/gl_FragData/g, "glFragData");
  354. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  355. }
  356. callback(result);
  357. };
  358. Effect.prototype._processIncludes = function (sourceCode, callback) {
  359. var _this = this;
  360. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  361. var match = regex.exec(sourceCode);
  362. var returnValue = new String(sourceCode);
  363. while (match != null) {
  364. var includeFile = match[1];
  365. // Uniform declaration
  366. if (includeFile.indexOf("__decl__") !== -1) {
  367. includeFile = includeFile.replace(/__decl__/, "");
  368. if (this._engine.supportsUniformBuffers) {
  369. includeFile = includeFile.replace(/Vertex/, "Ubo");
  370. includeFile = includeFile.replace(/Fragment/, "Ubo");
  371. }
  372. includeFile = includeFile + "Declaration";
  373. }
  374. if (Effect.IncludesShadersStore[includeFile]) {
  375. // Substitution
  376. var includeContent = Effect.IncludesShadersStore[includeFile];
  377. if (match[2]) {
  378. var splits = match[3].split(",");
  379. for (var index = 0; index < splits.length; index += 2) {
  380. var source = new RegExp(splits[index], "g");
  381. var dest = splits[index + 1];
  382. includeContent = includeContent.replace(source, dest);
  383. }
  384. }
  385. if (match[4]) {
  386. var indexString = match[5];
  387. if (indexString.indexOf("..") !== -1) {
  388. var indexSplits = indexString.split("..");
  389. var minIndex = parseInt(indexSplits[0]);
  390. var maxIndex = parseInt(indexSplits[1]);
  391. var sourceIncludeContent = includeContent.slice(0);
  392. includeContent = "";
  393. if (isNaN(maxIndex)) {
  394. maxIndex = this._indexParameters[indexSplits[1]];
  395. }
  396. for (var i = minIndex; i < maxIndex; i++) {
  397. if (!this._engine.supportsUniformBuffers) {
  398. // Ubo replacement
  399. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  400. return p1 + "{X}";
  401. });
  402. }
  403. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  404. }
  405. }
  406. else {
  407. if (!this._engine.supportsUniformBuffers) {
  408. // Ubo replacement
  409. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  410. return p1 + "{X}";
  411. });
  412. }
  413. includeContent = includeContent.replace(/\{X\}/g, indexString);
  414. }
  415. }
  416. // Replace
  417. returnValue = returnValue.replace(match[0], includeContent);
  418. }
  419. else {
  420. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  421. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  422. Effect.IncludesShadersStore[includeFile] = fileContent;
  423. _this._processIncludes(returnValue, callback);
  424. });
  425. return;
  426. }
  427. match = regex.exec(sourceCode);
  428. }
  429. callback(returnValue);
  430. };
  431. Effect.prototype._processPrecision = function (source) {
  432. if (source.indexOf("precision highp float") === -1) {
  433. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  434. source = "precision mediump float;\n" + source;
  435. }
  436. else {
  437. source = "precision highp float;\n" + source;
  438. }
  439. }
  440. else {
  441. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  442. source = source.replace("precision highp float", "precision mediump float");
  443. }
  444. }
  445. return source;
  446. };
  447. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  448. var _this = this;
  449. this._isReady = false;
  450. this._vertexSourceCodeOverride = vertexSourceCode;
  451. this._fragmentSourceCodeOverride = fragmentSourceCode;
  452. this.onError = function (effect, error) {
  453. if (onError) {
  454. onError(error);
  455. }
  456. };
  457. this.onCompiled = function () {
  458. var scenes = _this.getEngine().scenes;
  459. for (var i = 0; i < scenes.length; i++) {
  460. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  461. }
  462. if (onCompiled) {
  463. onCompiled(_this._program);
  464. }
  465. };
  466. this._fallbacks = null;
  467. this._prepareEffect();
  468. };
  469. Effect.prototype.getSpecificUniformLocations = function (names) {
  470. var engine = this._engine;
  471. return engine.getUniforms(this._program, names);
  472. };
  473. Effect.prototype._prepareEffect = function () {
  474. var attributesNames = this._attributesNames;
  475. var defines = this.defines;
  476. var fallbacks = this._fallbacks;
  477. this._valueCache = {};
  478. var previousProgram = this._program;
  479. try {
  480. var engine = this._engine;
  481. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  482. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  483. }
  484. else {
  485. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  486. }
  487. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  488. if (engine.supportsUniformBuffers) {
  489. for (var name in this._uniformBuffersNames) {
  490. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  491. }
  492. }
  493. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  494. this._attributes = engine.getAttributes(this._program, attributesNames);
  495. var index;
  496. for (index = 0; index < this._samplers.length; index++) {
  497. var sampler = this.getUniform(this._samplers[index]);
  498. if (sampler == null) {
  499. this._samplers.splice(index, 1);
  500. index--;
  501. }
  502. }
  503. engine.bindSamplers(this);
  504. this._compilationError = "";
  505. this._isReady = true;
  506. if (this.onCompiled) {
  507. this.onCompiled(this);
  508. }
  509. this.onCompileObservable.notifyObservers(this);
  510. this.onCompileObservable.clear();
  511. // Unbind mesh reference in fallbacks
  512. if (this._fallbacks) {
  513. this._fallbacks.unBindMesh();
  514. }
  515. if (previousProgram) {
  516. this.getEngine()._deleteProgram(previousProgram);
  517. }
  518. }
  519. catch (e) {
  520. this._compilationError = e.message;
  521. // Let's go through fallbacks then
  522. BABYLON.Tools.Error("Unable to compile effect:");
  523. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  524. return " " + uniform;
  525. }));
  526. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  527. return " " + attribute;
  528. }));
  529. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  530. BABYLON.Tools.Error("Error: " + this._compilationError);
  531. if (previousProgram) {
  532. this._program = previousProgram;
  533. this._isReady = true;
  534. if (this.onError) {
  535. this.onError(this, this._compilationError);
  536. }
  537. this.onErrorObservable.notifyObservers(this);
  538. }
  539. if (fallbacks && fallbacks.isMoreFallbacks) {
  540. BABYLON.Tools.Error("Trying next fallback.");
  541. this.defines = fallbacks.reduce(this.defines);
  542. this._prepareEffect();
  543. }
  544. else {
  545. if (this.onError) {
  546. this.onError(this, this._compilationError);
  547. }
  548. this.onErrorObservable.notifyObservers(this);
  549. this.onErrorObservable.clear();
  550. // Unbind mesh reference in fallbacks
  551. if (this._fallbacks) {
  552. this._fallbacks.unBindMesh();
  553. }
  554. }
  555. }
  556. };
  557. Object.defineProperty(Effect.prototype, "isSupported", {
  558. get: function () {
  559. return this._compilationError === "";
  560. },
  561. enumerable: true,
  562. configurable: true
  563. });
  564. Effect.prototype._bindTexture = function (channel, texture) {
  565. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  566. };
  567. Effect.prototype.setTexture = function (channel, texture) {
  568. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  569. };
  570. Effect.prototype.setTextureArray = function (channel, textures) {
  571. if (this._samplers.indexOf(channel + "Ex") === -1) {
  572. var initialPos = this._samplers.indexOf(channel);
  573. for (var index = 1; index < textures.length; index++) {
  574. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  575. }
  576. }
  577. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  578. };
  579. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  580. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  581. };
  582. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  583. var cache = this._valueCache[uniformName];
  584. var flag = matrix.updateFlag;
  585. if (cache !== undefined && cache === flag) {
  586. return false;
  587. }
  588. this._valueCache[uniformName] = flag;
  589. return true;
  590. };
  591. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  592. var cache = this._valueCache[uniformName];
  593. if (!cache) {
  594. cache = [x, y];
  595. this._valueCache[uniformName] = cache;
  596. return true;
  597. }
  598. var changed = false;
  599. if (cache[0] !== x) {
  600. cache[0] = x;
  601. changed = true;
  602. }
  603. if (cache[1] !== y) {
  604. cache[1] = y;
  605. changed = true;
  606. }
  607. return changed;
  608. };
  609. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  610. var cache = this._valueCache[uniformName];
  611. if (!cache) {
  612. cache = [x, y, z];
  613. this._valueCache[uniformName] = cache;
  614. return true;
  615. }
  616. var changed = false;
  617. if (cache[0] !== x) {
  618. cache[0] = x;
  619. changed = true;
  620. }
  621. if (cache[1] !== y) {
  622. cache[1] = y;
  623. changed = true;
  624. }
  625. if (cache[2] !== z) {
  626. cache[2] = z;
  627. changed = true;
  628. }
  629. return changed;
  630. };
  631. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  632. var cache = this._valueCache[uniformName];
  633. if (!cache) {
  634. cache = [x, y, z, w];
  635. this._valueCache[uniformName] = cache;
  636. return true;
  637. }
  638. var changed = false;
  639. if (cache[0] !== x) {
  640. cache[0] = x;
  641. changed = true;
  642. }
  643. if (cache[1] !== y) {
  644. cache[1] = y;
  645. changed = true;
  646. }
  647. if (cache[2] !== z) {
  648. cache[2] = z;
  649. changed = true;
  650. }
  651. if (cache[3] !== w) {
  652. cache[3] = w;
  653. changed = true;
  654. }
  655. return changed;
  656. };
  657. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  658. var bufferName = this._uniformBuffersNames[name];
  659. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  660. return;
  661. }
  662. Effect._baseCache[bufferName] = buffer;
  663. this._engine.bindUniformBufferBase(buffer, bufferName);
  664. };
  665. Effect.prototype.bindUniformBlock = function (blockName, index) {
  666. this._engine.bindUniformBlock(this._program, blockName, index);
  667. };
  668. Effect.prototype.setInt = function (uniformName, value) {
  669. var cache = this._valueCache[uniformName];
  670. if (cache !== undefined && cache === value)
  671. return this;
  672. this._valueCache[uniformName] = value;
  673. this._engine.setInt(this.getUniform(uniformName), value);
  674. return this;
  675. };
  676. Effect.prototype.setIntArray = function (uniformName, array) {
  677. this._valueCache[uniformName] = null;
  678. this._engine.setIntArray(this.getUniform(uniformName), array);
  679. return this;
  680. };
  681. Effect.prototype.setIntArray2 = function (uniformName, array) {
  682. this._valueCache[uniformName] = null;
  683. this._engine.setIntArray2(this.getUniform(uniformName), array);
  684. return this;
  685. };
  686. Effect.prototype.setIntArray3 = function (uniformName, array) {
  687. this._valueCache[uniformName] = null;
  688. this._engine.setIntArray3(this.getUniform(uniformName), array);
  689. return this;
  690. };
  691. Effect.prototype.setIntArray4 = function (uniformName, array) {
  692. this._valueCache[uniformName] = null;
  693. this._engine.setIntArray4(this.getUniform(uniformName), array);
  694. return this;
  695. };
  696. Effect.prototype.setFloatArray = function (uniformName, array) {
  697. this._valueCache[uniformName] = null;
  698. this._engine.setFloatArray(this.getUniform(uniformName), array);
  699. return this;
  700. };
  701. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  702. this._valueCache[uniformName] = null;
  703. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  704. return this;
  705. };
  706. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  707. this._valueCache[uniformName] = null;
  708. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  709. return this;
  710. };
  711. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  712. this._valueCache[uniformName] = null;
  713. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  714. return this;
  715. };
  716. Effect.prototype.setArray = function (uniformName, array) {
  717. this._valueCache[uniformName] = null;
  718. this._engine.setArray(this.getUniform(uniformName), array);
  719. return this;
  720. };
  721. Effect.prototype.setArray2 = function (uniformName, array) {
  722. this._valueCache[uniformName] = null;
  723. this._engine.setArray2(this.getUniform(uniformName), array);
  724. return this;
  725. };
  726. Effect.prototype.setArray3 = function (uniformName, array) {
  727. this._valueCache[uniformName] = null;
  728. this._engine.setArray3(this.getUniform(uniformName), array);
  729. return this;
  730. };
  731. Effect.prototype.setArray4 = function (uniformName, array) {
  732. this._valueCache[uniformName] = null;
  733. this._engine.setArray4(this.getUniform(uniformName), array);
  734. return this;
  735. };
  736. Effect.prototype.setMatrices = function (uniformName, matrices) {
  737. if (!matrices) {
  738. return this;
  739. }
  740. this._valueCache[uniformName] = null;
  741. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  742. return this;
  743. };
  744. Effect.prototype.setMatrix = function (uniformName, matrix) {
  745. if (this._cacheMatrix(uniformName, matrix)) {
  746. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  747. }
  748. return this;
  749. };
  750. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  751. this._valueCache[uniformName] = null;
  752. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  753. return this;
  754. };
  755. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  756. this._valueCache[uniformName] = null;
  757. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  758. return this;
  759. };
  760. Effect.prototype.setFloat = function (uniformName, value) {
  761. var cache = this._valueCache[uniformName];
  762. if (cache !== undefined && cache === value)
  763. return this;
  764. this._valueCache[uniformName] = value;
  765. this._engine.setFloat(this.getUniform(uniformName), value);
  766. return this;
  767. };
  768. Effect.prototype.setBool = function (uniformName, bool) {
  769. var cache = this._valueCache[uniformName];
  770. if (cache !== undefined && cache === bool)
  771. return this;
  772. this._valueCache[uniformName] = bool;
  773. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  774. return this;
  775. };
  776. Effect.prototype.setVector2 = function (uniformName, vector2) {
  777. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  778. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  779. }
  780. return this;
  781. };
  782. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  783. if (this._cacheFloat2(uniformName, x, y)) {
  784. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  785. }
  786. return this;
  787. };
  788. Effect.prototype.setVector3 = function (uniformName, vector3) {
  789. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  790. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  791. }
  792. return this;
  793. };
  794. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  795. if (this._cacheFloat3(uniformName, x, y, z)) {
  796. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  797. }
  798. return this;
  799. };
  800. Effect.prototype.setVector4 = function (uniformName, vector4) {
  801. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  802. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  803. }
  804. return this;
  805. };
  806. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  807. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  808. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  809. }
  810. return this;
  811. };
  812. Effect.prototype.setColor3 = function (uniformName, color3) {
  813. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  814. this._engine.setColor3(this.getUniform(uniformName), color3);
  815. }
  816. return this;
  817. };
  818. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  819. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  820. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  821. }
  822. return this;
  823. };
  824. Effect.ResetCache = function () {
  825. Effect._baseCache = {};
  826. };
  827. Effect._uniqueIdSeed = 0;
  828. Effect._baseCache = {};
  829. // Statics
  830. Effect.ShadersStore = {};
  831. Effect.IncludesShadersStore = {};
  832. return Effect;
  833. }());
  834. BABYLON.Effect = Effect;
  835. })(BABYLON || (BABYLON = {}));
  836. //# sourceMappingURL=babylon.effect.js.map
  837. //# sourceMappingURL=babylon.types.js.map
  838. var BABYLON;
  839. (function (BABYLON) {
  840. var KeyboardEventTypes = /** @class */ (function () {
  841. function KeyboardEventTypes() {
  842. }
  843. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  844. get: function () {
  845. return KeyboardEventTypes._KEYDOWN;
  846. },
  847. enumerable: true,
  848. configurable: true
  849. });
  850. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  851. get: function () {
  852. return KeyboardEventTypes._KEYUP;
  853. },
  854. enumerable: true,
  855. configurable: true
  856. });
  857. KeyboardEventTypes._KEYDOWN = 0x01;
  858. KeyboardEventTypes._KEYUP = 0x02;
  859. return KeyboardEventTypes;
  860. }());
  861. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  862. var KeyboardInfo = /** @class */ (function () {
  863. function KeyboardInfo(type, event) {
  864. this.type = type;
  865. this.event = event;
  866. }
  867. return KeyboardInfo;
  868. }());
  869. BABYLON.KeyboardInfo = KeyboardInfo;
  870. /**
  871. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  872. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  873. */
  874. var KeyboardInfoPre = /** @class */ (function (_super) {
  875. __extends(KeyboardInfoPre, _super);
  876. function KeyboardInfoPre(type, event) {
  877. var _this = _super.call(this, type, event) || this;
  878. _this.skipOnPointerObservable = false;
  879. return _this;
  880. }
  881. return KeyboardInfoPre;
  882. }(KeyboardInfo));
  883. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  884. })(BABYLON || (BABYLON = {}));
  885. //# sourceMappingURL=babylon.keyboardEvents.js.map
  886. var BABYLON;
  887. (function (BABYLON) {
  888. var PointerEventTypes = /** @class */ (function () {
  889. function PointerEventTypes() {
  890. }
  891. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  892. get: function () {
  893. return PointerEventTypes._POINTERDOWN;
  894. },
  895. enumerable: true,
  896. configurable: true
  897. });
  898. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  899. get: function () {
  900. return PointerEventTypes._POINTERUP;
  901. },
  902. enumerable: true,
  903. configurable: true
  904. });
  905. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  906. get: function () {
  907. return PointerEventTypes._POINTERMOVE;
  908. },
  909. enumerable: true,
  910. configurable: true
  911. });
  912. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  913. get: function () {
  914. return PointerEventTypes._POINTERWHEEL;
  915. },
  916. enumerable: true,
  917. configurable: true
  918. });
  919. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  920. get: function () {
  921. return PointerEventTypes._POINTERPICK;
  922. },
  923. enumerable: true,
  924. configurable: true
  925. });
  926. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  927. get: function () {
  928. return PointerEventTypes._POINTERTAP;
  929. },
  930. enumerable: true,
  931. configurable: true
  932. });
  933. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  934. get: function () {
  935. return PointerEventTypes._POINTERDOUBLETAP;
  936. },
  937. enumerable: true,
  938. configurable: true
  939. });
  940. PointerEventTypes._POINTERDOWN = 0x01;
  941. PointerEventTypes._POINTERUP = 0x02;
  942. PointerEventTypes._POINTERMOVE = 0x04;
  943. PointerEventTypes._POINTERWHEEL = 0x08;
  944. PointerEventTypes._POINTERPICK = 0x10;
  945. PointerEventTypes._POINTERTAP = 0x20;
  946. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  947. return PointerEventTypes;
  948. }());
  949. BABYLON.PointerEventTypes = PointerEventTypes;
  950. var PointerInfoBase = /** @class */ (function () {
  951. function PointerInfoBase(type, event) {
  952. this.type = type;
  953. this.event = event;
  954. }
  955. return PointerInfoBase;
  956. }());
  957. BABYLON.PointerInfoBase = PointerInfoBase;
  958. /**
  959. * This class is used to store pointer related info for the onPrePointerObservable event.
  960. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  961. */
  962. var PointerInfoPre = /** @class */ (function (_super) {
  963. __extends(PointerInfoPre, _super);
  964. function PointerInfoPre(type, event, localX, localY) {
  965. var _this = _super.call(this, type, event) || this;
  966. _this.skipOnPointerObservable = false;
  967. _this.localPosition = new BABYLON.Vector2(localX, localY);
  968. return _this;
  969. }
  970. return PointerInfoPre;
  971. }(PointerInfoBase));
  972. BABYLON.PointerInfoPre = PointerInfoPre;
  973. /**
  974. * This type contains all the data related to a pointer event in Babylon.js.
  975. * 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.
  976. */
  977. var PointerInfo = /** @class */ (function (_super) {
  978. __extends(PointerInfo, _super);
  979. function PointerInfo(type, event, pickInfo) {
  980. var _this = _super.call(this, type, event) || this;
  981. _this.pickInfo = pickInfo;
  982. return _this;
  983. }
  984. return PointerInfo;
  985. }(PointerInfoBase));
  986. BABYLON.PointerInfo = PointerInfo;
  987. })(BABYLON || (BABYLON = {}));
  988. //# sourceMappingURL=babylon.pointerEvents.js.map
  989. var BABYLON;
  990. (function (BABYLON) {
  991. BABYLON.ToGammaSpace = 1 / 2.2;
  992. BABYLON.ToLinearSpace = 2.2;
  993. BABYLON.Epsilon = 0.001;
  994. var Color3 = /** @class */ (function () {
  995. /**
  996. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  997. */
  998. function Color3(r, g, b) {
  999. if (r === void 0) { r = 0; }
  1000. if (g === void 0) { g = 0; }
  1001. if (b === void 0) { b = 0; }
  1002. this.r = r;
  1003. this.g = g;
  1004. this.b = b;
  1005. }
  1006. /**
  1007. * Returns a string with the Color3 current values.
  1008. */
  1009. Color3.prototype.toString = function () {
  1010. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1011. };
  1012. /**
  1013. * Returns the string "Color3".
  1014. */
  1015. Color3.prototype.getClassName = function () {
  1016. return "Color3";
  1017. };
  1018. /**
  1019. * Returns the Color3 hash code.
  1020. */
  1021. Color3.prototype.getHashCode = function () {
  1022. var hash = this.r || 0;
  1023. hash = (hash * 397) ^ (this.g || 0);
  1024. hash = (hash * 397) ^ (this.b || 0);
  1025. return hash;
  1026. };
  1027. // Operators
  1028. /**
  1029. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  1030. * Returns the Color3.
  1031. */
  1032. Color3.prototype.toArray = function (array, index) {
  1033. if (index === undefined) {
  1034. index = 0;
  1035. }
  1036. array[index] = this.r;
  1037. array[index + 1] = this.g;
  1038. array[index + 2] = this.b;
  1039. return this;
  1040. };
  1041. /**
  1042. * Returns a new Color4 object from the current Color3 and the passed alpha.
  1043. */
  1044. Color3.prototype.toColor4 = function (alpha) {
  1045. if (alpha === void 0) { alpha = 1; }
  1046. return new Color4(this.r, this.g, this.b, alpha);
  1047. };
  1048. /**
  1049. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  1050. */
  1051. Color3.prototype.asArray = function () {
  1052. var result = new Array();
  1053. this.toArray(result, 0);
  1054. return result;
  1055. };
  1056. /**
  1057. * Returns the luminance value (float).
  1058. */
  1059. Color3.prototype.toLuminance = function () {
  1060. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1061. };
  1062. /**
  1063. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  1064. * Returns this new object.
  1065. */
  1066. Color3.prototype.multiply = function (otherColor) {
  1067. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1068. };
  1069. /**
  1070. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  1071. * Returns the current Color3.
  1072. */
  1073. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1074. result.r = this.r * otherColor.r;
  1075. result.g = this.g * otherColor.g;
  1076. result.b = this.b * otherColor.b;
  1077. return this;
  1078. };
  1079. /**
  1080. * Boolean : True if the rgb values are equal to the passed ones.
  1081. */
  1082. Color3.prototype.equals = function (otherColor) {
  1083. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1084. };
  1085. /**
  1086. * Boolean : True if the rgb values are equal to the passed ones.
  1087. */
  1088. Color3.prototype.equalsFloats = function (r, g, b) {
  1089. return this.r === r && this.g === g && this.b === b;
  1090. };
  1091. /**
  1092. * Multiplies in place each rgb value by scale.
  1093. * Returns the updated Color3.
  1094. */
  1095. Color3.prototype.scale = function (scale) {
  1096. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1097. };
  1098. /**
  1099. * Multiplies the rgb values by scale and stores the result into "result".
  1100. * Returns the unmodified current Color3.
  1101. */
  1102. Color3.prototype.scaleToRef = function (scale, result) {
  1103. result.r = this.r * scale;
  1104. result.g = this.g * scale;
  1105. result.b = this.b * scale;
  1106. return this;
  1107. };
  1108. /**
  1109. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  1110. */
  1111. Color3.prototype.add = function (otherColor) {
  1112. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1113. };
  1114. /**
  1115. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  1116. * Returns the unmodified current Color3.
  1117. */
  1118. Color3.prototype.addToRef = function (otherColor, result) {
  1119. result.r = this.r + otherColor.r;
  1120. result.g = this.g + otherColor.g;
  1121. result.b = this.b + otherColor.b;
  1122. return this;
  1123. };
  1124. /**
  1125. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  1126. */
  1127. Color3.prototype.subtract = function (otherColor) {
  1128. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1129. };
  1130. /**
  1131. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  1132. * Returns the unmodified current Color3.
  1133. */
  1134. Color3.prototype.subtractToRef = function (otherColor, result) {
  1135. result.r = this.r - otherColor.r;
  1136. result.g = this.g - otherColor.g;
  1137. result.b = this.b - otherColor.b;
  1138. return this;
  1139. };
  1140. /**
  1141. * Returns a new Color3 copied the current one.
  1142. */
  1143. Color3.prototype.clone = function () {
  1144. return new Color3(this.r, this.g, this.b);
  1145. };
  1146. /**
  1147. * Copies the rgb values from the source in the current Color3.
  1148. * Returns the updated Color3.
  1149. */
  1150. Color3.prototype.copyFrom = function (source) {
  1151. this.r = source.r;
  1152. this.g = source.g;
  1153. this.b = source.b;
  1154. return this;
  1155. };
  1156. /**
  1157. * Updates the Color3 rgb values from the passed floats.
  1158. * Returns the Color3.
  1159. */
  1160. Color3.prototype.copyFromFloats = function (r, g, b) {
  1161. this.r = r;
  1162. this.g = g;
  1163. this.b = b;
  1164. return this;
  1165. };
  1166. /**
  1167. * Updates the Color3 rgb values from the passed floats.
  1168. * Returns the Color3.
  1169. */
  1170. Color3.prototype.set = function (r, g, b) {
  1171. return this.copyFromFloats(r, g, b);
  1172. };
  1173. /**
  1174. * Returns the Color3 hexadecimal code as a string.
  1175. */
  1176. Color3.prototype.toHexString = function () {
  1177. var intR = (this.r * 255) | 0;
  1178. var intG = (this.g * 255) | 0;
  1179. var intB = (this.b * 255) | 0;
  1180. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1181. };
  1182. /**
  1183. * Returns a new Color3 converted to linear space.
  1184. */
  1185. Color3.prototype.toLinearSpace = function () {
  1186. var convertedColor = new Color3();
  1187. this.toLinearSpaceToRef(convertedColor);
  1188. return convertedColor;
  1189. };
  1190. /**
  1191. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  1192. * Returns the unmodified Color3.
  1193. */
  1194. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1195. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1196. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1197. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1198. return this;
  1199. };
  1200. /**
  1201. * Returns a new Color3 converted to gamma space.
  1202. */
  1203. Color3.prototype.toGammaSpace = function () {
  1204. var convertedColor = new Color3();
  1205. this.toGammaSpaceToRef(convertedColor);
  1206. return convertedColor;
  1207. };
  1208. /**
  1209. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  1210. * Returns the unmodified Color3.
  1211. */
  1212. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1213. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1214. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1215. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1216. return this;
  1217. };
  1218. // Statics
  1219. /**
  1220. * Creates a new Color3 from the string containing valid hexadecimal values.
  1221. */
  1222. Color3.FromHexString = function (hex) {
  1223. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1224. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1225. return new Color3(0, 0, 0);
  1226. }
  1227. var r = parseInt(hex.substring(1, 3), 16);
  1228. var g = parseInt(hex.substring(3, 5), 16);
  1229. var b = parseInt(hex.substring(5, 7), 16);
  1230. return Color3.FromInts(r, g, b);
  1231. };
  1232. /**
  1233. * Creates a new Vector3 from the startind index of the passed array.
  1234. */
  1235. Color3.FromArray = function (array, offset) {
  1236. if (offset === void 0) { offset = 0; }
  1237. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1238. };
  1239. /**
  1240. * Creates a new Color3 from integer values ( < 256).
  1241. */
  1242. Color3.FromInts = function (r, g, b) {
  1243. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1244. };
  1245. /**
  1246. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  1247. */
  1248. Color3.Lerp = function (start, end, amount) {
  1249. var r = start.r + ((end.r - start.r) * amount);
  1250. var g = start.g + ((end.g - start.g) * amount);
  1251. var b = start.b + ((end.b - start.b) * amount);
  1252. return new Color3(r, g, b);
  1253. };
  1254. Color3.Red = function () { return new Color3(1, 0, 0); };
  1255. Color3.Green = function () { return new Color3(0, 1, 0); };
  1256. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1257. Color3.Black = function () { return new Color3(0, 0, 0); };
  1258. Color3.White = function () { return new Color3(1, 1, 1); };
  1259. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1260. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1261. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1262. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1263. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1264. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1265. return Color3;
  1266. }());
  1267. BABYLON.Color3 = Color3;
  1268. var Color4 = /** @class */ (function () {
  1269. /**
  1270. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  1271. */
  1272. function Color4(r, g, b, a) {
  1273. if (r === void 0) { r = 0; }
  1274. if (g === void 0) { g = 0; }
  1275. if (b === void 0) { b = 0; }
  1276. if (a === void 0) { a = 1; }
  1277. this.r = r;
  1278. this.g = g;
  1279. this.b = b;
  1280. this.a = a;
  1281. }
  1282. // Operators
  1283. /**
  1284. * Adds in place the passed Color4 values to the current Color4.
  1285. * Returns the updated Color4.
  1286. */
  1287. Color4.prototype.addInPlace = function (right) {
  1288. this.r += right.r;
  1289. this.g += right.g;
  1290. this.b += right.b;
  1291. this.a += right.a;
  1292. return this;
  1293. };
  1294. /**
  1295. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  1296. */
  1297. Color4.prototype.asArray = function () {
  1298. var result = new Array();
  1299. this.toArray(result, 0);
  1300. return result;
  1301. };
  1302. /**
  1303. * Stores from the starting index in the passed array the Color4 successive values.
  1304. * Returns the Color4.
  1305. */
  1306. Color4.prototype.toArray = function (array, index) {
  1307. if (index === undefined) {
  1308. index = 0;
  1309. }
  1310. array[index] = this.r;
  1311. array[index + 1] = this.g;
  1312. array[index + 2] = this.b;
  1313. array[index + 3] = this.a;
  1314. return this;
  1315. };
  1316. /**
  1317. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  1318. */
  1319. Color4.prototype.add = function (right) {
  1320. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1321. };
  1322. /**
  1323. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  1324. */
  1325. Color4.prototype.subtract = function (right) {
  1326. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1327. };
  1328. /**
  1329. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  1330. * Returns the Color4.
  1331. */
  1332. Color4.prototype.subtractToRef = function (right, result) {
  1333. result.r = this.r - right.r;
  1334. result.g = this.g - right.g;
  1335. result.b = this.b - right.b;
  1336. result.a = this.a - right.a;
  1337. return this;
  1338. };
  1339. /**
  1340. * Creates a new Color4 with the current Color4 values multiplied by scale.
  1341. */
  1342. Color4.prototype.scale = function (scale) {
  1343. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1344. };
  1345. /**
  1346. * Multiplies the current Color4 values by scale and stores the result in "result".
  1347. * Returns the Color4.
  1348. */
  1349. Color4.prototype.scaleToRef = function (scale, result) {
  1350. result.r = this.r * scale;
  1351. result.g = this.g * scale;
  1352. result.b = this.b * scale;
  1353. result.a = this.a * scale;
  1354. return this;
  1355. };
  1356. /**
  1357. * Multipy an RGBA Color4 value by another and return a new Color4 object
  1358. * @param color The Color4 (RGBA) value to multiply by
  1359. * @returns A new Color4.
  1360. */
  1361. Color4.prototype.multiply = function (color) {
  1362. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1363. };
  1364. /**
  1365. * Multipy an RGBA Color4 value by another and push the result in a reference value
  1366. * @param color The Color4 (RGBA) value to multiply by
  1367. * @param result The Color4 (RGBA) to fill the result in
  1368. * @returns the result Color4.
  1369. */
  1370. Color4.prototype.multiplyToRef = function (color, result) {
  1371. result.r = this.r * color.r;
  1372. result.g = this.g * color.g;
  1373. result.b = this.b * color.b;
  1374. result.a = this.a * color.a;
  1375. return result;
  1376. };
  1377. /**
  1378. * Returns a string with the Color4 values.
  1379. */
  1380. Color4.prototype.toString = function () {
  1381. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1382. };
  1383. /**
  1384. * Returns the string "Color4"
  1385. */
  1386. Color4.prototype.getClassName = function () {
  1387. return "Color4";
  1388. };
  1389. /**
  1390. * Return the Color4 hash code as a number.
  1391. */
  1392. Color4.prototype.getHashCode = function () {
  1393. var hash = this.r || 0;
  1394. hash = (hash * 397) ^ (this.g || 0);
  1395. hash = (hash * 397) ^ (this.b || 0);
  1396. hash = (hash * 397) ^ (this.a || 0);
  1397. return hash;
  1398. };
  1399. /**
  1400. * Creates a new Color4 copied from the current one.
  1401. */
  1402. Color4.prototype.clone = function () {
  1403. return new Color4(this.r, this.g, this.b, this.a);
  1404. };
  1405. /**
  1406. * Copies the passed Color4 values into the current one.
  1407. * Returns the updated Color4.
  1408. */
  1409. Color4.prototype.copyFrom = function (source) {
  1410. this.r = source.r;
  1411. this.g = source.g;
  1412. this.b = source.b;
  1413. this.a = source.a;
  1414. return this;
  1415. };
  1416. /**
  1417. * Copies the passed float values into the current one.
  1418. * Returns the updated Color4.
  1419. */
  1420. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1421. this.r = r;
  1422. this.g = g;
  1423. this.b = b;
  1424. this.a = a;
  1425. return this;
  1426. };
  1427. /**
  1428. * Copies the passed float values into the current one.
  1429. * Returns the updated Color4.
  1430. */
  1431. Color4.prototype.set = function (r, g, b, a) {
  1432. return this.copyFromFloats(r, g, b, a);
  1433. };
  1434. /**
  1435. * Returns a string containing the hexadecimal Color4 code.
  1436. */
  1437. Color4.prototype.toHexString = function () {
  1438. var intR = (this.r * 255) | 0;
  1439. var intG = (this.g * 255) | 0;
  1440. var intB = (this.b * 255) | 0;
  1441. var intA = (this.a * 255) | 0;
  1442. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1443. };
  1444. /**
  1445. * Returns a new Color4 converted to linear space.
  1446. */
  1447. Color4.prototype.toLinearSpace = function () {
  1448. var convertedColor = new Color4();
  1449. this.toLinearSpaceToRef(convertedColor);
  1450. return convertedColor;
  1451. };
  1452. /**
  1453. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  1454. * Returns the unmodified Color4.
  1455. */
  1456. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1457. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1458. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1459. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1460. convertedColor.a = this.a;
  1461. return this;
  1462. };
  1463. /**
  1464. * Returns a new Color4 converted to gamma space.
  1465. */
  1466. Color4.prototype.toGammaSpace = function () {
  1467. var convertedColor = new Color4();
  1468. this.toGammaSpaceToRef(convertedColor);
  1469. return convertedColor;
  1470. };
  1471. /**
  1472. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  1473. * Returns the unmodified Color4.
  1474. */
  1475. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1476. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1477. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1478. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1479. convertedColor.a = this.a;
  1480. return this;
  1481. };
  1482. // Statics
  1483. /**
  1484. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  1485. */
  1486. Color4.FromHexString = function (hex) {
  1487. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1488. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1489. return new Color4(0.0, 0.0, 0.0, 0.0);
  1490. }
  1491. var r = parseInt(hex.substring(1, 3), 16);
  1492. var g = parseInt(hex.substring(3, 5), 16);
  1493. var b = parseInt(hex.substring(5, 7), 16);
  1494. var a = parseInt(hex.substring(7, 9), 16);
  1495. return Color4.FromInts(r, g, b, a);
  1496. };
  1497. /**
  1498. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1499. */
  1500. Color4.Lerp = function (left, right, amount) {
  1501. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1502. Color4.LerpToRef(left, right, amount, result);
  1503. return result;
  1504. };
  1505. /**
  1506. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1507. */
  1508. Color4.LerpToRef = function (left, right, amount, result) {
  1509. result.r = left.r + (right.r - left.r) * amount;
  1510. result.g = left.g + (right.g - left.g) * amount;
  1511. result.b = left.b + (right.b - left.b) * amount;
  1512. result.a = left.a + (right.a - left.a) * amount;
  1513. };
  1514. /**
  1515. * Creates a new Color4 from the starting index element of the passed array.
  1516. */
  1517. Color4.FromArray = function (array, offset) {
  1518. if (offset === void 0) { offset = 0; }
  1519. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1520. };
  1521. /**
  1522. * Creates a new Color4 from the passed integers ( < 256 ).
  1523. */
  1524. Color4.FromInts = function (r, g, b, a) {
  1525. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1526. };
  1527. Color4.CheckColors4 = function (colors, count) {
  1528. // Check if color3 was used
  1529. if (colors.length === count * 3) {
  1530. var colors4 = [];
  1531. for (var index = 0; index < colors.length; index += 3) {
  1532. var newIndex = (index / 3) * 4;
  1533. colors4[newIndex] = colors[index];
  1534. colors4[newIndex + 1] = colors[index + 1];
  1535. colors4[newIndex + 2] = colors[index + 2];
  1536. colors4[newIndex + 3] = 1.0;
  1537. }
  1538. return colors4;
  1539. }
  1540. return colors;
  1541. };
  1542. return Color4;
  1543. }());
  1544. BABYLON.Color4 = Color4;
  1545. var Vector2 = /** @class */ (function () {
  1546. /**
  1547. * Creates a new Vector2 from the passed x and y coordinates.
  1548. */
  1549. function Vector2(x, y) {
  1550. this.x = x;
  1551. this.y = y;
  1552. }
  1553. /**
  1554. * Returns a string with the Vector2 coordinates.
  1555. */
  1556. Vector2.prototype.toString = function () {
  1557. return "{X: " + this.x + " Y:" + this.y + "}";
  1558. };
  1559. /**
  1560. * Returns the string "Vector2"
  1561. */
  1562. Vector2.prototype.getClassName = function () {
  1563. return "Vector2";
  1564. };
  1565. /**
  1566. * Returns the Vector2 hash code as a number.
  1567. */
  1568. Vector2.prototype.getHashCode = function () {
  1569. var hash = this.x || 0;
  1570. hash = (hash * 397) ^ (this.y || 0);
  1571. return hash;
  1572. };
  1573. // Operators
  1574. /**
  1575. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1576. * Returns the Vector2.
  1577. */
  1578. Vector2.prototype.toArray = function (array, index) {
  1579. if (index === void 0) { index = 0; }
  1580. array[index] = this.x;
  1581. array[index + 1] = this.y;
  1582. return this;
  1583. };
  1584. /**
  1585. * Returns a new array with 2 elements : the Vector2 coordinates.
  1586. */
  1587. Vector2.prototype.asArray = function () {
  1588. var result = new Array();
  1589. this.toArray(result, 0);
  1590. return result;
  1591. };
  1592. /**
  1593. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1594. * Returns the updated Vector2.
  1595. */
  1596. Vector2.prototype.copyFrom = function (source) {
  1597. this.x = source.x;
  1598. this.y = source.y;
  1599. return this;
  1600. };
  1601. /**
  1602. * Sets the Vector2 coordinates with the passed floats.
  1603. * Returns the updated Vector2.
  1604. */
  1605. Vector2.prototype.copyFromFloats = function (x, y) {
  1606. this.x = x;
  1607. this.y = y;
  1608. return this;
  1609. };
  1610. /**
  1611. * Sets the Vector2 coordinates with the passed floats.
  1612. * Returns the updated Vector2.
  1613. */
  1614. Vector2.prototype.set = function (x, y) {
  1615. return this.copyFromFloats(x, y);
  1616. };
  1617. /**
  1618. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1619. */
  1620. Vector2.prototype.add = function (otherVector) {
  1621. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1622. };
  1623. /**
  1624. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1625. * Returns the Vector2.
  1626. */
  1627. Vector2.prototype.addToRef = function (otherVector, result) {
  1628. result.x = this.x + otherVector.x;
  1629. result.y = this.y + otherVector.y;
  1630. return this;
  1631. };
  1632. /**
  1633. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1634. * Returns the updated Vector2.
  1635. */
  1636. Vector2.prototype.addInPlace = function (otherVector) {
  1637. this.x += otherVector.x;
  1638. this.y += otherVector.y;
  1639. return this;
  1640. };
  1641. /**
  1642. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1643. */
  1644. Vector2.prototype.addVector3 = function (otherVector) {
  1645. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1646. };
  1647. /**
  1648. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1649. */
  1650. Vector2.prototype.subtract = function (otherVector) {
  1651. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1652. };
  1653. /**
  1654. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1655. * Returns the Vector2.
  1656. */
  1657. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1658. result.x = this.x - otherVector.x;
  1659. result.y = this.y - otherVector.y;
  1660. return this;
  1661. };
  1662. /**
  1663. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1664. * Returns the updated Vector2.
  1665. */
  1666. Vector2.prototype.subtractInPlace = function (otherVector) {
  1667. this.x -= otherVector.x;
  1668. this.y -= otherVector.y;
  1669. return this;
  1670. };
  1671. /**
  1672. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1673. * Returns the updated Vector2.
  1674. */
  1675. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1676. this.x *= otherVector.x;
  1677. this.y *= otherVector.y;
  1678. return this;
  1679. };
  1680. /**
  1681. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1682. */
  1683. Vector2.prototype.multiply = function (otherVector) {
  1684. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1685. };
  1686. /**
  1687. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1688. * Returns the Vector2.
  1689. */
  1690. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1691. result.x = this.x * otherVector.x;
  1692. result.y = this.y * otherVector.y;
  1693. return this;
  1694. };
  1695. /**
  1696. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1697. */
  1698. Vector2.prototype.multiplyByFloats = function (x, y) {
  1699. return new Vector2(this.x * x, this.y * y);
  1700. };
  1701. /**
  1702. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1703. */
  1704. Vector2.prototype.divide = function (otherVector) {
  1705. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1706. };
  1707. /**
  1708. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1709. * Returns the Vector2.
  1710. */
  1711. Vector2.prototype.divideToRef = function (otherVector, result) {
  1712. result.x = this.x / otherVector.x;
  1713. result.y = this.y / otherVector.y;
  1714. return this;
  1715. };
  1716. /**
  1717. * Divides the current Vector3 coordinates by the passed ones.
  1718. * Returns the updated Vector3.
  1719. */
  1720. Vector2.prototype.divideInPlace = function (otherVector) {
  1721. return this.divideToRef(otherVector, this);
  1722. };
  1723. /**
  1724. * Returns a new Vector2 with current Vector2 negated coordinates.
  1725. */
  1726. Vector2.prototype.negate = function () {
  1727. return new Vector2(-this.x, -this.y);
  1728. };
  1729. /**
  1730. * Multiply the Vector2 coordinates by scale.
  1731. * Returns the updated Vector2.
  1732. */
  1733. Vector2.prototype.scaleInPlace = function (scale) {
  1734. this.x *= scale;
  1735. this.y *= scale;
  1736. return this;
  1737. };
  1738. /**
  1739. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1740. */
  1741. Vector2.prototype.scale = function (scale) {
  1742. return new Vector2(this.x * scale, this.y * scale);
  1743. };
  1744. /**
  1745. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1746. */
  1747. Vector2.prototype.equals = function (otherVector) {
  1748. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1749. };
  1750. /**
  1751. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1752. */
  1753. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1754. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1755. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1756. };
  1757. // Properties
  1758. /**
  1759. * Returns the vector length (float).
  1760. */
  1761. Vector2.prototype.length = function () {
  1762. return Math.sqrt(this.x * this.x + this.y * this.y);
  1763. };
  1764. /**
  1765. * Returns the vector squared length (float);
  1766. */
  1767. Vector2.prototype.lengthSquared = function () {
  1768. return (this.x * this.x + this.y * this.y);
  1769. };
  1770. // Methods
  1771. /**
  1772. * Normalize the vector.
  1773. * Returns the updated Vector2.
  1774. */
  1775. Vector2.prototype.normalize = function () {
  1776. var len = this.length();
  1777. if (len === 0)
  1778. return this;
  1779. var num = 1.0 / len;
  1780. this.x *= num;
  1781. this.y *= num;
  1782. return this;
  1783. };
  1784. /**
  1785. * Returns a new Vector2 copied from the Vector2.
  1786. */
  1787. Vector2.prototype.clone = function () {
  1788. return new Vector2(this.x, this.y);
  1789. };
  1790. // Statics
  1791. /**
  1792. * Returns a new Vector2(0, 0)
  1793. */
  1794. Vector2.Zero = function () {
  1795. return new Vector2(0, 0);
  1796. };
  1797. /**
  1798. * Returns a new Vector2(1, 1)
  1799. */
  1800. Vector2.One = function () {
  1801. return new Vector2(1, 1);
  1802. };
  1803. /**
  1804. * Returns a new Vector2 set from the passed index element of the passed array.
  1805. */
  1806. Vector2.FromArray = function (array, offset) {
  1807. if (offset === void 0) { offset = 0; }
  1808. return new Vector2(array[offset], array[offset + 1]);
  1809. };
  1810. /**
  1811. * Sets "result" from the passed index element of the passed array.
  1812. */
  1813. Vector2.FromArrayToRef = function (array, offset, result) {
  1814. result.x = array[offset];
  1815. result.y = array[offset + 1];
  1816. };
  1817. /**
  1818. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  1819. */
  1820. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  1821. var squared = amount * amount;
  1822. var cubed = amount * squared;
  1823. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1824. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1825. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1826. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1827. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1828. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1829. return new Vector2(x, y);
  1830. };
  1831. /**
  1832. * 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".
  1833. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1834. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1835. */
  1836. Vector2.Clamp = function (value, min, max) {
  1837. var x = value.x;
  1838. x = (x > max.x) ? max.x : x;
  1839. x = (x < min.x) ? min.x : x;
  1840. var y = value.y;
  1841. y = (y > max.y) ? max.y : y;
  1842. y = (y < min.y) ? min.y : y;
  1843. return new Vector2(x, y);
  1844. };
  1845. /**
  1846. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1847. */
  1848. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1849. var squared = amount * amount;
  1850. var cubed = amount * squared;
  1851. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1852. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1853. var part3 = (cubed - (2.0 * squared)) + amount;
  1854. var part4 = cubed - squared;
  1855. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1856. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1857. return new Vector2(x, y);
  1858. };
  1859. /**
  1860. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1861. */
  1862. Vector2.Lerp = function (start, end, amount) {
  1863. var x = start.x + ((end.x - start.x) * amount);
  1864. var y = start.y + ((end.y - start.y) * amount);
  1865. return new Vector2(x, y);
  1866. };
  1867. /**
  1868. * Returns the dot product (float) of the vector "left" and the vector "right".
  1869. */
  1870. Vector2.Dot = function (left, right) {
  1871. return left.x * right.x + left.y * right.y;
  1872. };
  1873. /**
  1874. * Returns a new Vector2 equal to the normalized passed vector.
  1875. */
  1876. Vector2.Normalize = function (vector) {
  1877. var newVector = vector.clone();
  1878. newVector.normalize();
  1879. return newVector;
  1880. };
  1881. /**
  1882. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1883. */
  1884. Vector2.Minimize = function (left, right) {
  1885. var x = (left.x < right.x) ? left.x : right.x;
  1886. var y = (left.y < right.y) ? left.y : right.y;
  1887. return new Vector2(x, y);
  1888. };
  1889. /**
  1890. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1891. */
  1892. Vector2.Maximize = function (left, right) {
  1893. var x = (left.x > right.x) ? left.x : right.x;
  1894. var y = (left.y > right.y) ? left.y : right.y;
  1895. return new Vector2(x, y);
  1896. };
  1897. /**
  1898. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1899. */
  1900. Vector2.Transform = function (vector, transformation) {
  1901. var r = Vector2.Zero();
  1902. Vector2.TransformToRef(vector, transformation, r);
  1903. return r;
  1904. };
  1905. /**
  1906. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1907. */
  1908. Vector2.TransformToRef = function (vector, transformation, result) {
  1909. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1910. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1911. result.x = x;
  1912. result.y = y;
  1913. };
  1914. /**
  1915. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1916. */
  1917. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1918. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1919. var sign = a < 0 ? -1 : 1;
  1920. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1921. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1922. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1923. };
  1924. /**
  1925. * Returns the distance (float) between the vectors "value1" and "value2".
  1926. */
  1927. Vector2.Distance = function (value1, value2) {
  1928. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1929. };
  1930. /**
  1931. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1932. */
  1933. Vector2.DistanceSquared = function (value1, value2) {
  1934. var x = value1.x - value2.x;
  1935. var y = value1.y - value2.y;
  1936. return (x * x) + (y * y);
  1937. };
  1938. /**
  1939. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1940. */
  1941. Vector2.Center = function (value1, value2) {
  1942. var center = value1.add(value2);
  1943. center.scaleInPlace(0.5);
  1944. return center;
  1945. };
  1946. /**
  1947. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1948. */
  1949. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1950. var l2 = Vector2.DistanceSquared(segA, segB);
  1951. if (l2 === 0.0) {
  1952. return Vector2.Distance(p, segA);
  1953. }
  1954. var v = segB.subtract(segA);
  1955. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1956. var proj = segA.add(v.multiplyByFloats(t, t));
  1957. return Vector2.Distance(p, proj);
  1958. };
  1959. return Vector2;
  1960. }());
  1961. BABYLON.Vector2 = Vector2;
  1962. var Vector3 = /** @class */ (function () {
  1963. /**
  1964. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1965. * A Vector3 is the main object used in 3D geometry.
  1966. * It can represent etiher the coordinates of a point the space, either a direction.
  1967. */
  1968. function Vector3(x, y, z) {
  1969. this.x = x;
  1970. this.y = y;
  1971. this.z = z;
  1972. }
  1973. /**
  1974. * Returns a string with the Vector3 coordinates.
  1975. */
  1976. Vector3.prototype.toString = function () {
  1977. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1978. };
  1979. /**
  1980. * Returns the string "Vector3"
  1981. */
  1982. Vector3.prototype.getClassName = function () {
  1983. return "Vector3";
  1984. };
  1985. /**
  1986. * Returns the Vector hash code.
  1987. */
  1988. Vector3.prototype.getHashCode = function () {
  1989. var hash = this.x || 0;
  1990. hash = (hash * 397) ^ (this.y || 0);
  1991. hash = (hash * 397) ^ (this.z || 0);
  1992. return hash;
  1993. };
  1994. // Operators
  1995. /**
  1996. * Returns a new array with three elements : the coordinates the Vector3.
  1997. */
  1998. Vector3.prototype.asArray = function () {
  1999. var result = [];
  2000. this.toArray(result, 0);
  2001. return result;
  2002. };
  2003. /**
  2004. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2005. * Returns the Vector3.
  2006. */
  2007. Vector3.prototype.toArray = function (array, index) {
  2008. if (index === void 0) { index = 0; }
  2009. array[index] = this.x;
  2010. array[index + 1] = this.y;
  2011. array[index + 2] = this.z;
  2012. return this;
  2013. };
  2014. /**
  2015. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2016. */
  2017. Vector3.prototype.toQuaternion = function () {
  2018. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2019. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2020. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2021. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2022. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2023. var cosy = Math.cos(this.y * 0.5);
  2024. var siny = Math.sin(this.y * 0.5);
  2025. result.x = coszMinusx * siny;
  2026. result.y = -sinzMinusx * siny;
  2027. result.z = sinxPlusz * cosy;
  2028. result.w = cosxPlusz * cosy;
  2029. return result;
  2030. };
  2031. /**
  2032. * Adds the passed vector to the current Vector3.
  2033. * Returns the updated Vector3.
  2034. */
  2035. Vector3.prototype.addInPlace = function (otherVector) {
  2036. this.x += otherVector.x;
  2037. this.y += otherVector.y;
  2038. this.z += otherVector.z;
  2039. return this;
  2040. };
  2041. /**
  2042. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2043. */
  2044. Vector3.prototype.add = function (otherVector) {
  2045. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2046. };
  2047. /**
  2048. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2049. * Returns the current Vector3.
  2050. */
  2051. Vector3.prototype.addToRef = function (otherVector, result) {
  2052. result.x = this.x + otherVector.x;
  2053. result.y = this.y + otherVector.y;
  2054. result.z = this.z + otherVector.z;
  2055. return this;
  2056. };
  2057. /**
  2058. * Subtract the passed vector from the current Vector3.
  2059. * Returns the updated Vector3.
  2060. */
  2061. Vector3.prototype.subtractInPlace = function (otherVector) {
  2062. this.x -= otherVector.x;
  2063. this.y -= otherVector.y;
  2064. this.z -= otherVector.z;
  2065. return this;
  2066. };
  2067. /**
  2068. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2069. */
  2070. Vector3.prototype.subtract = function (otherVector) {
  2071. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2072. };
  2073. /**
  2074. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2075. * Returns the current Vector3.
  2076. */
  2077. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2078. result.x = this.x - otherVector.x;
  2079. result.y = this.y - otherVector.y;
  2080. result.z = this.z - otherVector.z;
  2081. return this;
  2082. };
  2083. /**
  2084. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2085. */
  2086. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2087. return new Vector3(this.x - x, this.y - y, this.z - z);
  2088. };
  2089. /**
  2090. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2091. * Returns the current Vector3.
  2092. */
  2093. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2094. result.x = this.x - x;
  2095. result.y = this.y - y;
  2096. result.z = this.z - z;
  2097. return this;
  2098. };
  2099. /**
  2100. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2101. */
  2102. Vector3.prototype.negate = function () {
  2103. return new Vector3(-this.x, -this.y, -this.z);
  2104. };
  2105. /**
  2106. * Multiplies the Vector3 coordinates by the float "scale".
  2107. * Returns the updated Vector3.
  2108. */
  2109. Vector3.prototype.scaleInPlace = function (scale) {
  2110. this.x *= scale;
  2111. this.y *= scale;
  2112. this.z *= scale;
  2113. return this;
  2114. };
  2115. /**
  2116. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2117. */
  2118. Vector3.prototype.scale = function (scale) {
  2119. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2120. };
  2121. /**
  2122. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2123. * Returns the current Vector3.
  2124. */
  2125. Vector3.prototype.scaleToRef = function (scale, result) {
  2126. result.x = this.x * scale;
  2127. result.y = this.y * scale;
  2128. result.z = this.z * scale;
  2129. return this;
  2130. };
  2131. /**
  2132. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2133. */
  2134. Vector3.prototype.equals = function (otherVector) {
  2135. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2136. };
  2137. /**
  2138. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2139. */
  2140. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2141. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2142. 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);
  2143. };
  2144. /**
  2145. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2146. */
  2147. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2148. return this.x === x && this.y === y && this.z === z;
  2149. };
  2150. /**
  2151. * Muliplies the current Vector3 coordinates by the passed ones.
  2152. * Returns the updated Vector3.
  2153. */
  2154. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2155. this.x *= otherVector.x;
  2156. this.y *= otherVector.y;
  2157. this.z *= otherVector.z;
  2158. return this;
  2159. };
  2160. /**
  2161. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2162. */
  2163. Vector3.prototype.multiply = function (otherVector) {
  2164. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2165. };
  2166. /**
  2167. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2168. * Returns the current Vector3.
  2169. */
  2170. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2171. result.x = this.x * otherVector.x;
  2172. result.y = this.y * otherVector.y;
  2173. result.z = this.z * otherVector.z;
  2174. return this;
  2175. };
  2176. /**
  2177. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2178. */
  2179. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2180. return new Vector3(this.x * x, this.y * y, this.z * z);
  2181. };
  2182. /**
  2183. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2184. */
  2185. Vector3.prototype.divide = function (otherVector) {
  2186. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2187. };
  2188. /**
  2189. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2190. * Returns the current Vector3.
  2191. */
  2192. Vector3.prototype.divideToRef = function (otherVector, result) {
  2193. result.x = this.x / otherVector.x;
  2194. result.y = this.y / otherVector.y;
  2195. result.z = this.z / otherVector.z;
  2196. return this;
  2197. };
  2198. /**
  2199. * Divides the current Vector3 coordinates by the passed ones.
  2200. * Returns the updated Vector3.
  2201. */
  2202. Vector3.prototype.divideInPlace = function (otherVector) {
  2203. return this.divideToRef(otherVector, this);
  2204. };
  2205. /**
  2206. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2207. * Returns the updated Vector3.
  2208. */
  2209. Vector3.prototype.MinimizeInPlace = function (other) {
  2210. if (other.x < this.x)
  2211. this.x = other.x;
  2212. if (other.y < this.y)
  2213. this.y = other.y;
  2214. if (other.z < this.z)
  2215. this.z = other.z;
  2216. return this;
  2217. };
  2218. /**
  2219. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2220. * Returns the updated Vector3.
  2221. */
  2222. Vector3.prototype.MaximizeInPlace = function (other) {
  2223. if (other.x > this.x)
  2224. this.x = other.x;
  2225. if (other.y > this.y)
  2226. this.y = other.y;
  2227. if (other.z > this.z)
  2228. this.z = other.z;
  2229. return this;
  2230. };
  2231. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2232. /**
  2233. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2234. */
  2235. get: function () {
  2236. var absX = Math.abs(this.x);
  2237. var absY = Math.abs(this.y);
  2238. if (absX !== absY) {
  2239. return true;
  2240. }
  2241. var absZ = Math.abs(this.z);
  2242. if (absX !== absZ) {
  2243. return true;
  2244. }
  2245. if (absY !== absZ) {
  2246. return true;
  2247. }
  2248. return false;
  2249. },
  2250. enumerable: true,
  2251. configurable: true
  2252. });
  2253. // Properties
  2254. /**
  2255. * Returns the length of the Vector3 (float).
  2256. */
  2257. Vector3.prototype.length = function () {
  2258. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2259. };
  2260. /**
  2261. * Returns the squared length of the Vector3 (float).
  2262. */
  2263. Vector3.prototype.lengthSquared = function () {
  2264. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2265. };
  2266. /**
  2267. * Normalize the current Vector3.
  2268. * Returns the updated Vector3.
  2269. * /!\ In place operation.
  2270. */
  2271. Vector3.prototype.normalize = function () {
  2272. var len = this.length();
  2273. if (len === 0 || len === 1.0)
  2274. return this;
  2275. var num = 1.0 / len;
  2276. this.x *= num;
  2277. this.y *= num;
  2278. this.z *= num;
  2279. return this;
  2280. };
  2281. /**
  2282. * Normalize the current Vector3 to a new vector.
  2283. * @returns the new Vector3.
  2284. */
  2285. Vector3.prototype.normalizeToNew = function () {
  2286. var normalized = new Vector3(0, 0, 0);
  2287. this.normalizeToRef(normalized);
  2288. return normalized;
  2289. };
  2290. /**
  2291. * Normalize the current Vector3 to the reference.
  2292. * @param the reference to update.
  2293. * @returns the updated Vector3.
  2294. */
  2295. Vector3.prototype.normalizeToRef = function (reference) {
  2296. var len = this.length();
  2297. if (len === 0 || len === 1.0) {
  2298. reference.set(this.x, this.y, this.z);
  2299. return reference;
  2300. }
  2301. var scale = 1.0 / len;
  2302. this.scaleToRef(scale, reference);
  2303. return reference;
  2304. };
  2305. /**
  2306. * Returns a new Vector3 copied from the current Vector3.
  2307. */
  2308. Vector3.prototype.clone = function () {
  2309. return new Vector3(this.x, this.y, this.z);
  2310. };
  2311. /**
  2312. * Copies the passed vector coordinates to the current Vector3 ones.
  2313. * Returns the updated Vector3.
  2314. */
  2315. Vector3.prototype.copyFrom = function (source) {
  2316. this.x = source.x;
  2317. this.y = source.y;
  2318. this.z = source.z;
  2319. return this;
  2320. };
  2321. /**
  2322. * Copies the passed floats to the current Vector3 coordinates.
  2323. * Returns the updated Vector3.
  2324. */
  2325. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2326. this.x = x;
  2327. this.y = y;
  2328. this.z = z;
  2329. return this;
  2330. };
  2331. /**
  2332. * Copies the passed floats to the current Vector3 coordinates.
  2333. * Returns the updated Vector3.
  2334. */
  2335. Vector3.prototype.set = function (x, y, z) {
  2336. return this.copyFromFloats(x, y, z);
  2337. };
  2338. // Statics
  2339. /**
  2340. *
  2341. */
  2342. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2343. var d0 = Vector3.Dot(vector0, axis) - size;
  2344. var d1 = Vector3.Dot(vector1, axis) - size;
  2345. var s = d0 / (d0 - d1);
  2346. return s;
  2347. };
  2348. /**
  2349. * Returns a new Vector3 set from the index "offset" of the passed array.
  2350. */
  2351. Vector3.FromArray = function (array, offset) {
  2352. if (!offset) {
  2353. offset = 0;
  2354. }
  2355. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2356. };
  2357. /**
  2358. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2359. * This function is deprecated. Use FromArray instead.
  2360. */
  2361. Vector3.FromFloatArray = function (array, offset) {
  2362. return Vector3.FromArray(array, offset);
  2363. };
  2364. /**
  2365. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2366. */
  2367. Vector3.FromArrayToRef = function (array, offset, result) {
  2368. result.x = array[offset];
  2369. result.y = array[offset + 1];
  2370. result.z = array[offset + 2];
  2371. };
  2372. /**
  2373. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2374. * This function is deprecated. Use FromArrayToRef instead.
  2375. */
  2376. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2377. return Vector3.FromArrayToRef(array, offset, result);
  2378. };
  2379. /**
  2380. * Sets the passed vector "result" with the passed floats.
  2381. */
  2382. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2383. result.x = x;
  2384. result.y = y;
  2385. result.z = z;
  2386. };
  2387. /**
  2388. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2389. */
  2390. Vector3.Zero = function () {
  2391. return new Vector3(0.0, 0.0, 0.0);
  2392. };
  2393. /**
  2394. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2395. */
  2396. Vector3.One = function () {
  2397. return new Vector3(1.0, 1.0, 1.0);
  2398. };
  2399. /**
  2400. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2401. */
  2402. Vector3.Up = function () {
  2403. return new Vector3(0.0, 1.0, 0.0);
  2404. };
  2405. /**
  2406. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2407. */
  2408. Vector3.Forward = function () {
  2409. return new Vector3(0.0, 0.0, 1.0);
  2410. };
  2411. /**
  2412. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2413. */
  2414. Vector3.Right = function () {
  2415. return new Vector3(1.0, 0.0, 0.0);
  2416. };
  2417. /**
  2418. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2419. */
  2420. Vector3.Left = function () {
  2421. return new Vector3(-1.0, 0.0, 0.0);
  2422. };
  2423. /**
  2424. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2425. * This method computes tranformed coordinates only, not transformed direction vectors.
  2426. */
  2427. Vector3.TransformCoordinates = function (vector, transformation) {
  2428. var result = Vector3.Zero();
  2429. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2430. return result;
  2431. };
  2432. /**
  2433. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2434. * This method computes tranformed coordinates only, not transformed direction vectors.
  2435. */
  2436. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2437. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2438. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2439. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2440. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2441. result.x = x / w;
  2442. result.y = y / w;
  2443. result.z = z / w;
  2444. };
  2445. /**
  2446. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2447. * This method computes tranformed coordinates only, not transformed direction vectors.
  2448. */
  2449. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2450. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2451. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2452. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2453. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2454. result.x = rx / rw;
  2455. result.y = ry / rw;
  2456. result.z = rz / rw;
  2457. };
  2458. /**
  2459. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2460. * This methods computes transformed normalized direction vectors only.
  2461. */
  2462. Vector3.TransformNormal = function (vector, transformation) {
  2463. var result = Vector3.Zero();
  2464. Vector3.TransformNormalToRef(vector, transformation, result);
  2465. return result;
  2466. };
  2467. /**
  2468. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2469. * This methods computes transformed normalized direction vectors only.
  2470. */
  2471. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2472. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2473. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2474. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2475. result.x = x;
  2476. result.y = y;
  2477. result.z = z;
  2478. };
  2479. /**
  2480. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2481. * This methods computes transformed normalized direction vectors only.
  2482. */
  2483. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2484. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2485. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2486. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2487. };
  2488. /**
  2489. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2490. */
  2491. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2492. var squared = amount * amount;
  2493. var cubed = amount * squared;
  2494. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2495. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2496. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2497. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2498. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2499. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2500. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2501. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2502. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2503. return new Vector3(x, y, z);
  2504. };
  2505. /**
  2506. * 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".
  2507. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2508. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2509. */
  2510. Vector3.Clamp = function (value, min, max) {
  2511. var x = value.x;
  2512. x = (x > max.x) ? max.x : x;
  2513. x = (x < min.x) ? min.x : x;
  2514. var y = value.y;
  2515. y = (y > max.y) ? max.y : y;
  2516. y = (y < min.y) ? min.y : y;
  2517. var z = value.z;
  2518. z = (z > max.z) ? max.z : z;
  2519. z = (z < min.z) ? min.z : z;
  2520. return new Vector3(x, y, z);
  2521. };
  2522. /**
  2523. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2524. */
  2525. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2526. var squared = amount * amount;
  2527. var cubed = amount * squared;
  2528. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2529. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2530. var part3 = (cubed - (2.0 * squared)) + amount;
  2531. var part4 = cubed - squared;
  2532. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2533. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2534. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2535. return new Vector3(x, y, z);
  2536. };
  2537. /**
  2538. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2539. */
  2540. Vector3.Lerp = function (start, end, amount) {
  2541. var result = new Vector3(0, 0, 0);
  2542. Vector3.LerpToRef(start, end, amount, result);
  2543. return result;
  2544. };
  2545. /**
  2546. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2547. */
  2548. Vector3.LerpToRef = function (start, end, amount, result) {
  2549. result.x = start.x + ((end.x - start.x) * amount);
  2550. result.y = start.y + ((end.y - start.y) * amount);
  2551. result.z = start.z + ((end.z - start.z) * amount);
  2552. };
  2553. /**
  2554. * Returns the dot product (float) between the vectors "left" and "right".
  2555. */
  2556. Vector3.Dot = function (left, right) {
  2557. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2558. };
  2559. /**
  2560. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2561. * The cross product is then orthogonal to both "left" and "right".
  2562. */
  2563. Vector3.Cross = function (left, right) {
  2564. var result = Vector3.Zero();
  2565. Vector3.CrossToRef(left, right, result);
  2566. return result;
  2567. };
  2568. /**
  2569. * Sets the passed vector "result" with the cross product of "left" and "right".
  2570. * The cross product is then orthogonal to both "left" and "right".
  2571. */
  2572. Vector3.CrossToRef = function (left, right, result) {
  2573. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2574. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2575. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2576. result.copyFrom(MathTmp.Vector3[0]);
  2577. };
  2578. /**
  2579. * Returns a new Vector3 as the normalization of the passed vector.
  2580. */
  2581. Vector3.Normalize = function (vector) {
  2582. var result = Vector3.Zero();
  2583. Vector3.NormalizeToRef(vector, result);
  2584. return result;
  2585. };
  2586. /**
  2587. * Sets the passed vector "result" with the normalization of the passed first vector.
  2588. */
  2589. Vector3.NormalizeToRef = function (vector, result) {
  2590. result.copyFrom(vector);
  2591. result.normalize();
  2592. };
  2593. Vector3.Project = function (vector, world, transform, viewport) {
  2594. var cw = viewport.width;
  2595. var ch = viewport.height;
  2596. var cx = viewport.x;
  2597. var cy = viewport.y;
  2598. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2599. 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);
  2600. var matrix = MathTmp.Matrix[0];
  2601. world.multiplyToRef(transform, matrix);
  2602. matrix.multiplyToRef(viewportMatrix, matrix);
  2603. return Vector3.TransformCoordinates(vector, matrix);
  2604. };
  2605. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2606. var matrix = MathTmp.Matrix[0];
  2607. world.multiplyToRef(transform, matrix);
  2608. matrix.invert();
  2609. source.x = source.x / viewportWidth * 2 - 1;
  2610. source.y = -(source.y / viewportHeight * 2 - 1);
  2611. var vector = Vector3.TransformCoordinates(source, matrix);
  2612. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2613. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2614. vector = vector.scale(1.0 / num);
  2615. }
  2616. return vector;
  2617. };
  2618. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2619. var result = Vector3.Zero();
  2620. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2621. return result;
  2622. };
  2623. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2624. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2625. };
  2626. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2627. var matrix = MathTmp.Matrix[0];
  2628. world.multiplyToRef(view, matrix);
  2629. matrix.multiplyToRef(projection, matrix);
  2630. matrix.invert();
  2631. var screenSource = MathTmp.Vector3[0];
  2632. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2633. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2634. screenSource.z = 2 * sourceZ - 1.0;
  2635. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2636. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2637. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2638. result.scaleInPlace(1.0 / num);
  2639. }
  2640. };
  2641. Vector3.Minimize = function (left, right) {
  2642. var min = left.clone();
  2643. min.MinimizeInPlace(right);
  2644. return min;
  2645. };
  2646. Vector3.Maximize = function (left, right) {
  2647. var max = left.clone();
  2648. max.MaximizeInPlace(right);
  2649. return max;
  2650. };
  2651. /**
  2652. * Returns the distance (float) between the vectors "value1" and "value2".
  2653. */
  2654. Vector3.Distance = function (value1, value2) {
  2655. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2656. };
  2657. /**
  2658. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2659. */
  2660. Vector3.DistanceSquared = function (value1, value2) {
  2661. var x = value1.x - value2.x;
  2662. var y = value1.y - value2.y;
  2663. var z = value1.z - value2.z;
  2664. return (x * x) + (y * y) + (z * z);
  2665. };
  2666. /**
  2667. * Returns a new Vector3 located at the center between "value1" and "value2".
  2668. */
  2669. Vector3.Center = function (value1, value2) {
  2670. var center = value1.add(value2);
  2671. center.scaleInPlace(0.5);
  2672. return center;
  2673. };
  2674. /**
  2675. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2676. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2677. * to something in order to rotate it from its local system to the given target system.
  2678. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2679. * Returns a new Vector3.
  2680. */
  2681. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2682. var rotation = Vector3.Zero();
  2683. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2684. return rotation;
  2685. };
  2686. /**
  2687. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2688. */
  2689. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2690. var quat = MathTmp.Quaternion[0];
  2691. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2692. quat.toEulerAnglesToRef(ref);
  2693. };
  2694. return Vector3;
  2695. }());
  2696. BABYLON.Vector3 = Vector3;
  2697. //Vector4 class created for EulerAngle class conversion to Quaternion
  2698. var Vector4 = /** @class */ (function () {
  2699. /**
  2700. * Creates a Vector4 object from the passed floats.
  2701. */
  2702. function Vector4(x, y, z, w) {
  2703. this.x = x;
  2704. this.y = y;
  2705. this.z = z;
  2706. this.w = w;
  2707. }
  2708. /**
  2709. * Returns the string with the Vector4 coordinates.
  2710. */
  2711. Vector4.prototype.toString = function () {
  2712. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2713. };
  2714. /**
  2715. * Returns the string "Vector4".
  2716. */
  2717. Vector4.prototype.getClassName = function () {
  2718. return "Vector4";
  2719. };
  2720. /**
  2721. * Returns the Vector4 hash code.
  2722. */
  2723. Vector4.prototype.getHashCode = function () {
  2724. var hash = this.x || 0;
  2725. hash = (hash * 397) ^ (this.y || 0);
  2726. hash = (hash * 397) ^ (this.z || 0);
  2727. hash = (hash * 397) ^ (this.w || 0);
  2728. return hash;
  2729. };
  2730. // Operators
  2731. /**
  2732. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2733. */
  2734. Vector4.prototype.asArray = function () {
  2735. var result = new Array();
  2736. this.toArray(result, 0);
  2737. return result;
  2738. };
  2739. /**
  2740. * Populates the passed array from the passed index with the Vector4 coordinates.
  2741. * Returns the Vector4.
  2742. */
  2743. Vector4.prototype.toArray = function (array, index) {
  2744. if (index === undefined) {
  2745. index = 0;
  2746. }
  2747. array[index] = this.x;
  2748. array[index + 1] = this.y;
  2749. array[index + 2] = this.z;
  2750. array[index + 3] = this.w;
  2751. return this;
  2752. };
  2753. /**
  2754. * Adds the passed vector to the current Vector4.
  2755. * Returns the updated Vector4.
  2756. */
  2757. Vector4.prototype.addInPlace = function (otherVector) {
  2758. this.x += otherVector.x;
  2759. this.y += otherVector.y;
  2760. this.z += otherVector.z;
  2761. this.w += otherVector.w;
  2762. return this;
  2763. };
  2764. /**
  2765. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2766. */
  2767. Vector4.prototype.add = function (otherVector) {
  2768. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  2769. };
  2770. /**
  2771. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  2772. * Returns the current Vector4.
  2773. */
  2774. Vector4.prototype.addToRef = function (otherVector, result) {
  2775. result.x = this.x + otherVector.x;
  2776. result.y = this.y + otherVector.y;
  2777. result.z = this.z + otherVector.z;
  2778. result.w = this.w + otherVector.w;
  2779. return this;
  2780. };
  2781. /**
  2782. * Subtract in place the passed vector from the current Vector4.
  2783. * Returns the updated Vector4.
  2784. */
  2785. Vector4.prototype.subtractInPlace = function (otherVector) {
  2786. this.x -= otherVector.x;
  2787. this.y -= otherVector.y;
  2788. this.z -= otherVector.z;
  2789. this.w -= otherVector.w;
  2790. return this;
  2791. };
  2792. /**
  2793. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  2794. */
  2795. Vector4.prototype.subtract = function (otherVector) {
  2796. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2797. };
  2798. /**
  2799. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  2800. * Returns the current Vector4.
  2801. */
  2802. Vector4.prototype.subtractToRef = function (otherVector, result) {
  2803. result.x = this.x - otherVector.x;
  2804. result.y = this.y - otherVector.y;
  2805. result.z = this.z - otherVector.z;
  2806. result.w = this.w - otherVector.w;
  2807. return this;
  2808. };
  2809. /**
  2810. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2811. */
  2812. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2813. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2814. };
  2815. /**
  2816. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2817. * Returns the current Vector4.
  2818. */
  2819. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2820. result.x = this.x - x;
  2821. result.y = this.y - y;
  2822. result.z = this.z - z;
  2823. result.w = this.w - w;
  2824. return this;
  2825. };
  2826. /**
  2827. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2828. */
  2829. Vector4.prototype.negate = function () {
  2830. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2831. };
  2832. /**
  2833. * Multiplies the current Vector4 coordinates by scale (float).
  2834. * Returns the updated Vector4.
  2835. */
  2836. Vector4.prototype.scaleInPlace = function (scale) {
  2837. this.x *= scale;
  2838. this.y *= scale;
  2839. this.z *= scale;
  2840. this.w *= scale;
  2841. return this;
  2842. };
  2843. /**
  2844. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2845. */
  2846. Vector4.prototype.scale = function (scale) {
  2847. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2848. };
  2849. /**
  2850. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2851. * Returns the current Vector4.
  2852. */
  2853. Vector4.prototype.scaleToRef = function (scale, result) {
  2854. result.x = this.x * scale;
  2855. result.y = this.y * scale;
  2856. result.z = this.z * scale;
  2857. result.w = this.w * scale;
  2858. return this;
  2859. };
  2860. /**
  2861. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2862. */
  2863. Vector4.prototype.equals = function (otherVector) {
  2864. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2865. };
  2866. /**
  2867. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2868. */
  2869. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2870. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2871. return otherVector
  2872. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2873. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2874. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2875. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2876. };
  2877. /**
  2878. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2879. */
  2880. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2881. return this.x === x && this.y === y && this.z === z && this.w === w;
  2882. };
  2883. /**
  2884. * Multiplies in place the current Vector4 by the passed one.
  2885. * Returns the updated Vector4.
  2886. */
  2887. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2888. this.x *= otherVector.x;
  2889. this.y *= otherVector.y;
  2890. this.z *= otherVector.z;
  2891. this.w *= otherVector.w;
  2892. return this;
  2893. };
  2894. /**
  2895. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2896. */
  2897. Vector4.prototype.multiply = function (otherVector) {
  2898. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2899. };
  2900. /**
  2901. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2902. * Returns the current Vector4.
  2903. */
  2904. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2905. result.x = this.x * otherVector.x;
  2906. result.y = this.y * otherVector.y;
  2907. result.z = this.z * otherVector.z;
  2908. result.w = this.w * otherVector.w;
  2909. return this;
  2910. };
  2911. /**
  2912. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2913. */
  2914. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2915. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2916. };
  2917. /**
  2918. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2919. */
  2920. Vector4.prototype.divide = function (otherVector) {
  2921. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2922. };
  2923. /**
  2924. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2925. * Returns the current Vector4.
  2926. */
  2927. Vector4.prototype.divideToRef = function (otherVector, result) {
  2928. result.x = this.x / otherVector.x;
  2929. result.y = this.y / otherVector.y;
  2930. result.z = this.z / otherVector.z;
  2931. result.w = this.w / otherVector.w;
  2932. return this;
  2933. };
  2934. /**
  2935. * Divides the current Vector3 coordinates by the passed ones.
  2936. * Returns the updated Vector3.
  2937. */
  2938. Vector4.prototype.divideInPlace = function (otherVector) {
  2939. return this.divideToRef(otherVector, this);
  2940. };
  2941. /**
  2942. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2943. */
  2944. Vector4.prototype.MinimizeInPlace = function (other) {
  2945. if (other.x < this.x)
  2946. this.x = other.x;
  2947. if (other.y < this.y)
  2948. this.y = other.y;
  2949. if (other.z < this.z)
  2950. this.z = other.z;
  2951. if (other.w < this.w)
  2952. this.w = other.w;
  2953. return this;
  2954. };
  2955. /**
  2956. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2957. */
  2958. Vector4.prototype.MaximizeInPlace = function (other) {
  2959. if (other.x > this.x)
  2960. this.x = other.x;
  2961. if (other.y > this.y)
  2962. this.y = other.y;
  2963. if (other.z > this.z)
  2964. this.z = other.z;
  2965. if (other.w > this.w)
  2966. this.w = other.w;
  2967. return this;
  2968. };
  2969. // Properties
  2970. /**
  2971. * Returns the Vector4 length (float).
  2972. */
  2973. Vector4.prototype.length = function () {
  2974. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2975. };
  2976. /**
  2977. * Returns the Vector4 squared length (float).
  2978. */
  2979. Vector4.prototype.lengthSquared = function () {
  2980. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2981. };
  2982. // Methods
  2983. /**
  2984. * Normalizes in place the Vector4.
  2985. * Returns the updated Vector4.
  2986. */
  2987. Vector4.prototype.normalize = function () {
  2988. var len = this.length();
  2989. if (len === 0)
  2990. return this;
  2991. var num = 1.0 / len;
  2992. this.x *= num;
  2993. this.y *= num;
  2994. this.z *= num;
  2995. this.w *= num;
  2996. return this;
  2997. };
  2998. /**
  2999. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3000. */
  3001. Vector4.prototype.toVector3 = function () {
  3002. return new Vector3(this.x, this.y, this.z);
  3003. };
  3004. /**
  3005. * Returns a new Vector4 copied from the current one.
  3006. */
  3007. Vector4.prototype.clone = function () {
  3008. return new Vector4(this.x, this.y, this.z, this.w);
  3009. };
  3010. /**
  3011. * Updates the current Vector4 with the passed one coordinates.
  3012. * Returns the updated Vector4.
  3013. */
  3014. Vector4.prototype.copyFrom = function (source) {
  3015. this.x = source.x;
  3016. this.y = source.y;
  3017. this.z = source.z;
  3018. this.w = source.w;
  3019. return this;
  3020. };
  3021. /**
  3022. * Updates the current Vector4 coordinates with the passed floats.
  3023. * Returns the updated Vector4.
  3024. */
  3025. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3026. this.x = x;
  3027. this.y = y;
  3028. this.z = z;
  3029. this.w = w;
  3030. return this;
  3031. };
  3032. /**
  3033. * Updates the current Vector4 coordinates with the passed floats.
  3034. * Returns the updated Vector4.
  3035. */
  3036. Vector4.prototype.set = function (x, y, z, w) {
  3037. return this.copyFromFloats(x, y, z, w);
  3038. };
  3039. // Statics
  3040. /**
  3041. * Returns a new Vector4 set from the starting index of the passed array.
  3042. */
  3043. Vector4.FromArray = function (array, offset) {
  3044. if (!offset) {
  3045. offset = 0;
  3046. }
  3047. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3048. };
  3049. /**
  3050. * Updates the passed vector "result" from the starting index of the passed array.
  3051. */
  3052. Vector4.FromArrayToRef = function (array, offset, result) {
  3053. result.x = array[offset];
  3054. result.y = array[offset + 1];
  3055. result.z = array[offset + 2];
  3056. result.w = array[offset + 3];
  3057. };
  3058. /**
  3059. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3060. */
  3061. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3062. Vector4.FromArrayToRef(array, offset, result);
  3063. };
  3064. /**
  3065. * Updates the passed vector "result" coordinates from the passed floats.
  3066. */
  3067. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3068. result.x = x;
  3069. result.y = y;
  3070. result.z = z;
  3071. result.w = w;
  3072. };
  3073. /**
  3074. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3075. */
  3076. Vector4.Zero = function () {
  3077. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3078. };
  3079. /**
  3080. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3081. */
  3082. Vector4.One = function () {
  3083. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3084. };
  3085. /**
  3086. * Returns a new normalized Vector4 from the passed one.
  3087. */
  3088. Vector4.Normalize = function (vector) {
  3089. var result = Vector4.Zero();
  3090. Vector4.NormalizeToRef(vector, result);
  3091. return result;
  3092. };
  3093. /**
  3094. * Updates the passed vector "result" from the normalization of the passed one.
  3095. */
  3096. Vector4.NormalizeToRef = function (vector, result) {
  3097. result.copyFrom(vector);
  3098. result.normalize();
  3099. };
  3100. Vector4.Minimize = function (left, right) {
  3101. var min = left.clone();
  3102. min.MinimizeInPlace(right);
  3103. return min;
  3104. };
  3105. Vector4.Maximize = function (left, right) {
  3106. var max = left.clone();
  3107. max.MaximizeInPlace(right);
  3108. return max;
  3109. };
  3110. /**
  3111. * Returns the distance (float) between the vectors "value1" and "value2".
  3112. */
  3113. Vector4.Distance = function (value1, value2) {
  3114. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3115. };
  3116. /**
  3117. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3118. */
  3119. Vector4.DistanceSquared = function (value1, value2) {
  3120. var x = value1.x - value2.x;
  3121. var y = value1.y - value2.y;
  3122. var z = value1.z - value2.z;
  3123. var w = value1.w - value2.w;
  3124. return (x * x) + (y * y) + (z * z) + (w * w);
  3125. };
  3126. /**
  3127. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3128. */
  3129. Vector4.Center = function (value1, value2) {
  3130. var center = value1.add(value2);
  3131. center.scaleInPlace(0.5);
  3132. return center;
  3133. };
  3134. /**
  3135. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3136. * This methods computes transformed normalized direction vectors only.
  3137. */
  3138. Vector4.TransformNormal = function (vector, transformation) {
  3139. var result = Vector4.Zero();
  3140. Vector4.TransformNormalToRef(vector, transformation, result);
  3141. return result;
  3142. };
  3143. /**
  3144. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3145. * This methods computes transformed normalized direction vectors only.
  3146. */
  3147. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3148. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3149. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3150. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3151. result.x = x;
  3152. result.y = y;
  3153. result.z = z;
  3154. result.w = vector.w;
  3155. };
  3156. /**
  3157. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3158. * This methods computes transformed normalized direction vectors only.
  3159. */
  3160. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3161. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3162. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3163. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3164. result.w = w;
  3165. };
  3166. return Vector4;
  3167. }());
  3168. BABYLON.Vector4 = Vector4;
  3169. var Size = /** @class */ (function () {
  3170. /**
  3171. * Creates a Size object from the passed width and height (floats).
  3172. */
  3173. function Size(width, height) {
  3174. this.width = width;
  3175. this.height = height;
  3176. }
  3177. // Returns a string with the Size width and height.
  3178. Size.prototype.toString = function () {
  3179. return "{W: " + this.width + ", H: " + this.height + "}";
  3180. };
  3181. /**
  3182. * Returns the string "Size"
  3183. */
  3184. Size.prototype.getClassName = function () {
  3185. return "Size";
  3186. };
  3187. /**
  3188. * Returns the Size hash code.
  3189. */
  3190. Size.prototype.getHashCode = function () {
  3191. var hash = this.width || 0;
  3192. hash = (hash * 397) ^ (this.height || 0);
  3193. return hash;
  3194. };
  3195. /**
  3196. * Updates the current size from the passed one.
  3197. * Returns the updated Size.
  3198. */
  3199. Size.prototype.copyFrom = function (src) {
  3200. this.width = src.width;
  3201. this.height = src.height;
  3202. };
  3203. /**
  3204. * Updates in place the current Size from the passed floats.
  3205. * Returns the updated Size.
  3206. */
  3207. Size.prototype.copyFromFloats = function (width, height) {
  3208. this.width = width;
  3209. this.height = height;
  3210. return this;
  3211. };
  3212. /**
  3213. * Updates in place the current Size from the passed floats.
  3214. * Returns the updated Size.
  3215. */
  3216. Size.prototype.set = function (width, height) {
  3217. return this.copyFromFloats(width, height);
  3218. };
  3219. /**
  3220. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3221. */
  3222. Size.prototype.multiplyByFloats = function (w, h) {
  3223. return new Size(this.width * w, this.height * h);
  3224. };
  3225. /**
  3226. * Returns a new Size copied from the passed one.
  3227. */
  3228. Size.prototype.clone = function () {
  3229. return new Size(this.width, this.height);
  3230. };
  3231. /**
  3232. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3233. */
  3234. Size.prototype.equals = function (other) {
  3235. if (!other) {
  3236. return false;
  3237. }
  3238. return (this.width === other.width) && (this.height === other.height);
  3239. };
  3240. Object.defineProperty(Size.prototype, "surface", {
  3241. /**
  3242. * Returns the surface of the Size : width * height (float).
  3243. */
  3244. get: function () {
  3245. return this.width * this.height;
  3246. },
  3247. enumerable: true,
  3248. configurable: true
  3249. });
  3250. /**
  3251. * Returns a new Size set to (0.0, 0.0)
  3252. */
  3253. Size.Zero = function () {
  3254. return new Size(0.0, 0.0);
  3255. };
  3256. /**
  3257. * Returns a new Size set as the addition result of the current Size and the passed one.
  3258. */
  3259. Size.prototype.add = function (otherSize) {
  3260. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3261. return r;
  3262. };
  3263. /**
  3264. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3265. */
  3266. Size.prototype.subtract = function (otherSize) {
  3267. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3268. return r;
  3269. };
  3270. /**
  3271. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3272. */
  3273. Size.Lerp = function (start, end, amount) {
  3274. var w = start.width + ((end.width - start.width) * amount);
  3275. var h = start.height + ((end.height - start.height) * amount);
  3276. return new Size(w, h);
  3277. };
  3278. return Size;
  3279. }());
  3280. BABYLON.Size = Size;
  3281. var Quaternion = /** @class */ (function () {
  3282. /**
  3283. * Creates a new Quaternion from the passed floats.
  3284. */
  3285. function Quaternion(x, y, z, w) {
  3286. if (x === void 0) { x = 0.0; }
  3287. if (y === void 0) { y = 0.0; }
  3288. if (z === void 0) { z = 0.0; }
  3289. if (w === void 0) { w = 1.0; }
  3290. this.x = x;
  3291. this.y = y;
  3292. this.z = z;
  3293. this.w = w;
  3294. }
  3295. /**
  3296. * Returns a string with the Quaternion coordinates.
  3297. */
  3298. Quaternion.prototype.toString = function () {
  3299. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3300. };
  3301. /**
  3302. * Returns the string "Quaternion".
  3303. */
  3304. Quaternion.prototype.getClassName = function () {
  3305. return "Quaternion";
  3306. };
  3307. /**
  3308. * Returns the Quaternion hash code.
  3309. */
  3310. Quaternion.prototype.getHashCode = function () {
  3311. var hash = this.x || 0;
  3312. hash = (hash * 397) ^ (this.y || 0);
  3313. hash = (hash * 397) ^ (this.z || 0);
  3314. hash = (hash * 397) ^ (this.w || 0);
  3315. return hash;
  3316. };
  3317. /**
  3318. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3319. */
  3320. Quaternion.prototype.asArray = function () {
  3321. return [this.x, this.y, this.z, this.w];
  3322. };
  3323. /**
  3324. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3325. */
  3326. Quaternion.prototype.equals = function (otherQuaternion) {
  3327. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3328. };
  3329. /**
  3330. * Returns a new Quaternion copied from the current one.
  3331. */
  3332. Quaternion.prototype.clone = function () {
  3333. return new Quaternion(this.x, this.y, this.z, this.w);
  3334. };
  3335. /**
  3336. * Updates the current Quaternion from the passed one coordinates.
  3337. * Returns the updated Quaterion.
  3338. */
  3339. Quaternion.prototype.copyFrom = function (other) {
  3340. this.x = other.x;
  3341. this.y = other.y;
  3342. this.z = other.z;
  3343. this.w = other.w;
  3344. return this;
  3345. };
  3346. /**
  3347. * Updates the current Quaternion from the passed float coordinates.
  3348. * Returns the updated Quaterion.
  3349. */
  3350. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3351. this.x = x;
  3352. this.y = y;
  3353. this.z = z;
  3354. this.w = w;
  3355. return this;
  3356. };
  3357. /**
  3358. * Updates the current Quaternion from the passed float coordinates.
  3359. * Returns the updated Quaterion.
  3360. */
  3361. Quaternion.prototype.set = function (x, y, z, w) {
  3362. return this.copyFromFloats(x, y, z, w);
  3363. };
  3364. /**
  3365. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3366. */
  3367. Quaternion.prototype.add = function (other) {
  3368. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3369. };
  3370. /**
  3371. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3372. */
  3373. Quaternion.prototype.subtract = function (other) {
  3374. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3375. };
  3376. /**
  3377. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3378. */
  3379. Quaternion.prototype.scale = function (value) {
  3380. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3381. };
  3382. /**
  3383. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3384. */
  3385. Quaternion.prototype.multiply = function (q1) {
  3386. var result = new Quaternion(0, 0, 0, 1.0);
  3387. this.multiplyToRef(q1, result);
  3388. return result;
  3389. };
  3390. /**
  3391. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3392. * Returns the current Quaternion.
  3393. */
  3394. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3395. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3396. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3397. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3398. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3399. result.copyFromFloats(x, y, z, w);
  3400. return this;
  3401. };
  3402. /**
  3403. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3404. * Returns the updated Quaternion.
  3405. */
  3406. Quaternion.prototype.multiplyInPlace = function (q1) {
  3407. this.multiplyToRef(q1, this);
  3408. return this;
  3409. };
  3410. /**
  3411. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3412. * Returns the current Quaternion.
  3413. */
  3414. Quaternion.prototype.conjugateToRef = function (ref) {
  3415. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3416. return this;
  3417. };
  3418. /**
  3419. * Conjugates in place the current Quaternion.
  3420. * Returns the updated Quaternion.
  3421. */
  3422. Quaternion.prototype.conjugateInPlace = function () {
  3423. this.x *= -1;
  3424. this.y *= -1;
  3425. this.z *= -1;
  3426. return this;
  3427. };
  3428. /**
  3429. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3430. */
  3431. Quaternion.prototype.conjugate = function () {
  3432. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3433. return result;
  3434. };
  3435. /**
  3436. * Returns the Quaternion length (float).
  3437. */
  3438. Quaternion.prototype.length = function () {
  3439. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3440. };
  3441. /**
  3442. * Normalize in place the current Quaternion.
  3443. * Returns the updated Quaternion.
  3444. */
  3445. Quaternion.prototype.normalize = function () {
  3446. var length = 1.0 / this.length();
  3447. this.x *= length;
  3448. this.y *= length;
  3449. this.z *= length;
  3450. this.w *= length;
  3451. return this;
  3452. };
  3453. /**
  3454. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3455. */
  3456. Quaternion.prototype.toEulerAngles = function (order) {
  3457. if (order === void 0) { order = "YZX"; }
  3458. var result = Vector3.Zero();
  3459. this.toEulerAnglesToRef(result, order);
  3460. return result;
  3461. };
  3462. /**
  3463. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3464. * Returns the current Quaternion.
  3465. */
  3466. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3467. if (order === void 0) { order = "YZX"; }
  3468. var qz = this.z;
  3469. var qx = this.x;
  3470. var qy = this.y;
  3471. var qw = this.w;
  3472. var sqw = qw * qw;
  3473. var sqz = qz * qz;
  3474. var sqx = qx * qx;
  3475. var sqy = qy * qy;
  3476. var zAxisY = qy * qz - qx * qw;
  3477. var limit = .4999999;
  3478. if (zAxisY < -limit) {
  3479. result.y = 2 * Math.atan2(qy, qw);
  3480. result.x = Math.PI / 2;
  3481. result.z = 0;
  3482. }
  3483. else if (zAxisY > limit) {
  3484. result.y = 2 * Math.atan2(qy, qw);
  3485. result.x = -Math.PI / 2;
  3486. result.z = 0;
  3487. }
  3488. else {
  3489. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3490. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3491. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3492. }
  3493. return this;
  3494. };
  3495. /**
  3496. * Updates the passed rotation matrix with the current Quaternion values.
  3497. * Returns the current Quaternion.
  3498. */
  3499. Quaternion.prototype.toRotationMatrix = function (result) {
  3500. var xx = this.x * this.x;
  3501. var yy = this.y * this.y;
  3502. var zz = this.z * this.z;
  3503. var xy = this.x * this.y;
  3504. var zw = this.z * this.w;
  3505. var zx = this.z * this.x;
  3506. var yw = this.y * this.w;
  3507. var yz = this.y * this.z;
  3508. var xw = this.x * this.w;
  3509. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3510. result.m[1] = 2.0 * (xy + zw);
  3511. result.m[2] = 2.0 * (zx - yw);
  3512. result.m[3] = 0;
  3513. result.m[4] = 2.0 * (xy - zw);
  3514. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3515. result.m[6] = 2.0 * (yz + xw);
  3516. result.m[7] = 0;
  3517. result.m[8] = 2.0 * (zx + yw);
  3518. result.m[9] = 2.0 * (yz - xw);
  3519. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3520. result.m[11] = 0;
  3521. result.m[12] = 0;
  3522. result.m[13] = 0;
  3523. result.m[14] = 0;
  3524. result.m[15] = 1.0;
  3525. result._markAsUpdated();
  3526. return this;
  3527. };
  3528. /**
  3529. * Updates the current Quaternion from the passed rotation matrix values.
  3530. * Returns the updated Quaternion.
  3531. */
  3532. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3533. Quaternion.FromRotationMatrixToRef(matrix, this);
  3534. return this;
  3535. };
  3536. // Statics
  3537. /**
  3538. * Returns a new Quaternion set from the passed rotation matrix values.
  3539. */
  3540. Quaternion.FromRotationMatrix = function (matrix) {
  3541. var result = new Quaternion();
  3542. Quaternion.FromRotationMatrixToRef(matrix, result);
  3543. return result;
  3544. };
  3545. /**
  3546. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3547. */
  3548. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3549. var data = matrix.m;
  3550. var m11 = data[0], m12 = data[4], m13 = data[8];
  3551. var m21 = data[1], m22 = data[5], m23 = data[9];
  3552. var m31 = data[2], m32 = data[6], m33 = data[10];
  3553. var trace = m11 + m22 + m33;
  3554. var s;
  3555. if (trace > 0) {
  3556. s = 0.5 / Math.sqrt(trace + 1.0);
  3557. result.w = 0.25 / s;
  3558. result.x = (m32 - m23) * s;
  3559. result.y = (m13 - m31) * s;
  3560. result.z = (m21 - m12) * s;
  3561. }
  3562. else if (m11 > m22 && m11 > m33) {
  3563. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3564. result.w = (m32 - m23) / s;
  3565. result.x = 0.25 * s;
  3566. result.y = (m12 + m21) / s;
  3567. result.z = (m13 + m31) / s;
  3568. }
  3569. else if (m22 > m33) {
  3570. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3571. result.w = (m13 - m31) / s;
  3572. result.x = (m12 + m21) / s;
  3573. result.y = 0.25 * s;
  3574. result.z = (m23 + m32) / s;
  3575. }
  3576. else {
  3577. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3578. result.w = (m21 - m12) / s;
  3579. result.x = (m13 + m31) / s;
  3580. result.y = (m23 + m32) / s;
  3581. result.z = 0.25 * s;
  3582. }
  3583. };
  3584. /**
  3585. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3586. */
  3587. Quaternion.Zero = function () {
  3588. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3589. };
  3590. /**
  3591. * Returns a new Quaternion as the inverted current Quaternion.
  3592. */
  3593. Quaternion.Inverse = function (q) {
  3594. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3595. };
  3596. /**
  3597. * Returns the identity Quaternion.
  3598. */
  3599. Quaternion.Identity = function () {
  3600. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3601. };
  3602. Quaternion.IsIdentity = function (quaternion) {
  3603. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3604. };
  3605. /**
  3606. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3607. */
  3608. Quaternion.RotationAxis = function (axis, angle) {
  3609. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3610. };
  3611. /**
  3612. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3613. */
  3614. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3615. var sin = Math.sin(angle / 2);
  3616. axis.normalize();
  3617. result.w = Math.cos(angle / 2);
  3618. result.x = axis.x * sin;
  3619. result.y = axis.y * sin;
  3620. result.z = axis.z * sin;
  3621. return result;
  3622. };
  3623. /**
  3624. * Retuns a new Quaternion set from the starting index of the passed array.
  3625. */
  3626. Quaternion.FromArray = function (array, offset) {
  3627. if (!offset) {
  3628. offset = 0;
  3629. }
  3630. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3631. };
  3632. /**
  3633. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3634. */
  3635. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3636. var q = new Quaternion();
  3637. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3638. return q;
  3639. };
  3640. /**
  3641. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3642. */
  3643. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3644. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3645. var halfRoll = roll * 0.5;
  3646. var halfPitch = pitch * 0.5;
  3647. var halfYaw = yaw * 0.5;
  3648. var sinRoll = Math.sin(halfRoll);
  3649. var cosRoll = Math.cos(halfRoll);
  3650. var sinPitch = Math.sin(halfPitch);
  3651. var cosPitch = Math.cos(halfPitch);
  3652. var sinYaw = Math.sin(halfYaw);
  3653. var cosYaw = Math.cos(halfYaw);
  3654. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3655. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3656. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3657. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3658. };
  3659. /**
  3660. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3661. */
  3662. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3663. var result = new Quaternion();
  3664. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3665. return result;
  3666. };
  3667. /**
  3668. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3669. */
  3670. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3671. // Produces a quaternion from Euler angles in the z-x-z orientation
  3672. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3673. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3674. var halfBeta = beta * 0.5;
  3675. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3676. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3677. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3678. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3679. };
  3680. /**
  3681. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3682. * cf to Vector3.RotationFromAxis() documentation.
  3683. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3684. */
  3685. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3686. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3687. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3688. return quat;
  3689. };
  3690. /**
  3691. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3692. * cf to Vector3.RotationFromAxis() documentation.
  3693. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3694. */
  3695. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3696. var rotMat = MathTmp.Matrix[0];
  3697. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3698. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3699. };
  3700. Quaternion.Slerp = function (left, right, amount) {
  3701. var result = Quaternion.Identity();
  3702. Quaternion.SlerpToRef(left, right, amount, result);
  3703. return result;
  3704. };
  3705. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3706. var num2;
  3707. var num3;
  3708. var num = amount;
  3709. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3710. var flag = false;
  3711. if (num4 < 0) {
  3712. flag = true;
  3713. num4 = -num4;
  3714. }
  3715. if (num4 > 0.999999) {
  3716. num3 = 1 - num;
  3717. num2 = flag ? -num : num;
  3718. }
  3719. else {
  3720. var num5 = Math.acos(num4);
  3721. var num6 = (1.0 / Math.sin(num5));
  3722. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3723. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3724. }
  3725. result.x = (num3 * left.x) + (num2 * right.x);
  3726. result.y = (num3 * left.y) + (num2 * right.y);
  3727. result.z = (num3 * left.z) + (num2 * right.z);
  3728. result.w = (num3 * left.w) + (num2 * right.w);
  3729. };
  3730. /**
  3731. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3732. */
  3733. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3734. var squared = amount * amount;
  3735. var cubed = amount * squared;
  3736. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3737. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3738. var part3 = (cubed - (2.0 * squared)) + amount;
  3739. var part4 = cubed - squared;
  3740. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3741. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3742. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3743. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3744. return new Quaternion(x, y, z, w);
  3745. };
  3746. return Quaternion;
  3747. }());
  3748. BABYLON.Quaternion = Quaternion;
  3749. var Matrix = /** @class */ (function () {
  3750. function Matrix() {
  3751. this._isIdentity = false;
  3752. this._isIdentityDirty = true;
  3753. this.m = new Float32Array(16);
  3754. this._markAsUpdated();
  3755. }
  3756. Matrix.prototype._markAsUpdated = function () {
  3757. this.updateFlag = Matrix._updateFlagSeed++;
  3758. this._isIdentityDirty = true;
  3759. };
  3760. // Properties
  3761. /**
  3762. * Boolean : True is the matrix is the identity matrix
  3763. */
  3764. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3765. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3766. if (this._isIdentityDirty) {
  3767. this._isIdentityDirty = false;
  3768. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  3769. this._isIdentity = false;
  3770. }
  3771. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  3772. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  3773. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  3774. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  3775. this._isIdentity = false;
  3776. }
  3777. else {
  3778. this._isIdentity = true;
  3779. }
  3780. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  3781. this._isIdentity = false;
  3782. }
  3783. }
  3784. return this._isIdentity;
  3785. };
  3786. /**
  3787. * Returns the matrix determinant (float).
  3788. */
  3789. Matrix.prototype.determinant = function () {
  3790. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  3791. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  3792. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  3793. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  3794. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  3795. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  3796. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  3797. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  3798. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  3799. };
  3800. // Methods
  3801. /**
  3802. * Returns the matrix underlying array.
  3803. */
  3804. Matrix.prototype.toArray = function () {
  3805. return this.m;
  3806. };
  3807. /**
  3808. * Returns the matrix underlying array.
  3809. */
  3810. Matrix.prototype.asArray = function () {
  3811. return this.toArray();
  3812. };
  3813. /**
  3814. * Inverts in place the Matrix.
  3815. * Returns the Matrix inverted.
  3816. */
  3817. Matrix.prototype.invert = function () {
  3818. this.invertToRef(this);
  3819. return this;
  3820. };
  3821. /**
  3822. * Sets all the matrix elements to zero.
  3823. * Returns the Matrix.
  3824. */
  3825. Matrix.prototype.reset = function () {
  3826. for (var index = 0; index < 16; index++) {
  3827. this.m[index] = 0.0;
  3828. }
  3829. this._markAsUpdated();
  3830. return this;
  3831. };
  3832. /**
  3833. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3834. */
  3835. Matrix.prototype.add = function (other) {
  3836. var result = new Matrix();
  3837. this.addToRef(other, result);
  3838. return result;
  3839. };
  3840. /**
  3841. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3842. * Returns the Matrix.
  3843. */
  3844. Matrix.prototype.addToRef = function (other, result) {
  3845. for (var index = 0; index < 16; index++) {
  3846. result.m[index] = this.m[index] + other.m[index];
  3847. }
  3848. result._markAsUpdated();
  3849. return this;
  3850. };
  3851. /**
  3852. * Adds in place the passed matrix to the current Matrix.
  3853. * Returns the updated Matrix.
  3854. */
  3855. Matrix.prototype.addToSelf = function (other) {
  3856. for (var index = 0; index < 16; index++) {
  3857. this.m[index] += other.m[index];
  3858. }
  3859. this._markAsUpdated();
  3860. return this;
  3861. };
  3862. /**
  3863. * Sets the passed matrix with the current inverted Matrix.
  3864. * Returns the unmodified current Matrix.
  3865. */
  3866. Matrix.prototype.invertToRef = function (other) {
  3867. var l1 = this.m[0];
  3868. var l2 = this.m[1];
  3869. var l3 = this.m[2];
  3870. var l4 = this.m[3];
  3871. var l5 = this.m[4];
  3872. var l6 = this.m[5];
  3873. var l7 = this.m[6];
  3874. var l8 = this.m[7];
  3875. var l9 = this.m[8];
  3876. var l10 = this.m[9];
  3877. var l11 = this.m[10];
  3878. var l12 = this.m[11];
  3879. var l13 = this.m[12];
  3880. var l14 = this.m[13];
  3881. var l15 = this.m[14];
  3882. var l16 = this.m[15];
  3883. var l17 = (l11 * l16) - (l12 * l15);
  3884. var l18 = (l10 * l16) - (l12 * l14);
  3885. var l19 = (l10 * l15) - (l11 * l14);
  3886. var l20 = (l9 * l16) - (l12 * l13);
  3887. var l21 = (l9 * l15) - (l11 * l13);
  3888. var l22 = (l9 * l14) - (l10 * l13);
  3889. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3890. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3891. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3892. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3893. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3894. var l28 = (l7 * l16) - (l8 * l15);
  3895. var l29 = (l6 * l16) - (l8 * l14);
  3896. var l30 = (l6 * l15) - (l7 * l14);
  3897. var l31 = (l5 * l16) - (l8 * l13);
  3898. var l32 = (l5 * l15) - (l7 * l13);
  3899. var l33 = (l5 * l14) - (l6 * l13);
  3900. var l34 = (l7 * l12) - (l8 * l11);
  3901. var l35 = (l6 * l12) - (l8 * l10);
  3902. var l36 = (l6 * l11) - (l7 * l10);
  3903. var l37 = (l5 * l12) - (l8 * l9);
  3904. var l38 = (l5 * l11) - (l7 * l9);
  3905. var l39 = (l5 * l10) - (l6 * l9);
  3906. other.m[0] = l23 * l27;
  3907. other.m[4] = l24 * l27;
  3908. other.m[8] = l25 * l27;
  3909. other.m[12] = l26 * l27;
  3910. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3911. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3912. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3913. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3914. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3915. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3916. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3917. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3918. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3919. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3920. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3921. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3922. other._markAsUpdated();
  3923. return this;
  3924. };
  3925. /**
  3926. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3927. * Returns the updated Matrix.
  3928. */
  3929. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3930. this.m[12] = x;
  3931. this.m[13] = y;
  3932. this.m[14] = z;
  3933. this._markAsUpdated();
  3934. return this;
  3935. };
  3936. /**
  3937. * Inserts the translation vector in the current Matrix.
  3938. * Returns the updated Matrix.
  3939. */
  3940. Matrix.prototype.setTranslation = function (vector3) {
  3941. this.m[12] = vector3.x;
  3942. this.m[13] = vector3.y;
  3943. this.m[14] = vector3.z;
  3944. this._markAsUpdated();
  3945. return this;
  3946. };
  3947. /**
  3948. * Returns a new Vector3 as the extracted translation from the Matrix.
  3949. */
  3950. Matrix.prototype.getTranslation = function () {
  3951. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3952. };
  3953. /**
  3954. * Fill a Vector3 with the extracted translation from the Matrix.
  3955. */
  3956. Matrix.prototype.getTranslationToRef = function (result) {
  3957. result.x = this.m[12];
  3958. result.y = this.m[13];
  3959. result.z = this.m[14];
  3960. return this;
  3961. };
  3962. /**
  3963. * Remove rotation and scaling part from the Matrix.
  3964. * Returns the updated Matrix.
  3965. */
  3966. Matrix.prototype.removeRotationAndScaling = function () {
  3967. this.setRowFromFloats(0, 1, 0, 0, 0);
  3968. this.setRowFromFloats(1, 0, 1, 0, 0);
  3969. this.setRowFromFloats(2, 0, 0, 1, 0);
  3970. return this;
  3971. };
  3972. /**
  3973. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3974. */
  3975. Matrix.prototype.multiply = function (other) {
  3976. var result = new Matrix();
  3977. this.multiplyToRef(other, result);
  3978. return result;
  3979. };
  3980. /**
  3981. * Updates the current Matrix from the passed one values.
  3982. * Returns the updated Matrix.
  3983. */
  3984. Matrix.prototype.copyFrom = function (other) {
  3985. for (var index = 0; index < 16; index++) {
  3986. this.m[index] = other.m[index];
  3987. }
  3988. this._markAsUpdated();
  3989. return this;
  3990. };
  3991. /**
  3992. * Populates the passed array from the starting index with the Matrix values.
  3993. * Returns the Matrix.
  3994. */
  3995. Matrix.prototype.copyToArray = function (array, offset) {
  3996. if (offset === void 0) { offset = 0; }
  3997. for (var index = 0; index < 16; index++) {
  3998. array[offset + index] = this.m[index];
  3999. }
  4000. return this;
  4001. };
  4002. /**
  4003. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4004. */
  4005. Matrix.prototype.multiplyToRef = function (other, result) {
  4006. this.multiplyToArray(other, result.m, 0);
  4007. result._markAsUpdated();
  4008. return this;
  4009. };
  4010. /**
  4011. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4012. */
  4013. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4014. var tm0 = this.m[0];
  4015. var tm1 = this.m[1];
  4016. var tm2 = this.m[2];
  4017. var tm3 = this.m[3];
  4018. var tm4 = this.m[4];
  4019. var tm5 = this.m[5];
  4020. var tm6 = this.m[6];
  4021. var tm7 = this.m[7];
  4022. var tm8 = this.m[8];
  4023. var tm9 = this.m[9];
  4024. var tm10 = this.m[10];
  4025. var tm11 = this.m[11];
  4026. var tm12 = this.m[12];
  4027. var tm13 = this.m[13];
  4028. var tm14 = this.m[14];
  4029. var tm15 = this.m[15];
  4030. var om0 = other.m[0];
  4031. var om1 = other.m[1];
  4032. var om2 = other.m[2];
  4033. var om3 = other.m[3];
  4034. var om4 = other.m[4];
  4035. var om5 = other.m[5];
  4036. var om6 = other.m[6];
  4037. var om7 = other.m[7];
  4038. var om8 = other.m[8];
  4039. var om9 = other.m[9];
  4040. var om10 = other.m[10];
  4041. var om11 = other.m[11];
  4042. var om12 = other.m[12];
  4043. var om13 = other.m[13];
  4044. var om14 = other.m[14];
  4045. var om15 = other.m[15];
  4046. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4047. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4048. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4049. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4050. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4051. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4052. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4053. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4054. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4055. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4056. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4057. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4058. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4059. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4060. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4061. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4062. return this;
  4063. };
  4064. /**
  4065. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4066. */
  4067. Matrix.prototype.equals = function (value) {
  4068. return value &&
  4069. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4070. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4071. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4072. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4073. };
  4074. /**
  4075. * Returns a new Matrix from the current Matrix.
  4076. */
  4077. Matrix.prototype.clone = function () {
  4078. 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]);
  4079. };
  4080. /**
  4081. * Returns the string "Matrix"
  4082. */
  4083. Matrix.prototype.getClassName = function () {
  4084. return "Matrix";
  4085. };
  4086. /**
  4087. * Returns the Matrix hash code.
  4088. */
  4089. Matrix.prototype.getHashCode = function () {
  4090. var hash = this.m[0] || 0;
  4091. for (var i = 1; i < 16; i++) {
  4092. hash = (hash * 397) ^ (this.m[i] || 0);
  4093. }
  4094. return hash;
  4095. };
  4096. /**
  4097. * Decomposes the current Matrix into :
  4098. * - a scale vector3 passed as a reference to update,
  4099. * - a rotation quaternion passed as a reference to update,
  4100. * - a translation vector3 passed as a reference to update.
  4101. * Returns the boolean `true`.
  4102. */
  4103. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4104. translation.x = this.m[12];
  4105. translation.y = this.m[13];
  4106. translation.z = this.m[14];
  4107. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4108. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4109. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4110. if (this.determinant() <= 0) {
  4111. scale.y *= -1;
  4112. }
  4113. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4114. rotation.x = 0;
  4115. rotation.y = 0;
  4116. rotation.z = 0;
  4117. rotation.w = 1;
  4118. return false;
  4119. }
  4120. 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]);
  4121. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4122. return true;
  4123. };
  4124. /**
  4125. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4126. */
  4127. Matrix.prototype.getRotationMatrix = function () {
  4128. var result = Matrix.Identity();
  4129. this.getRotationMatrixToRef(result);
  4130. return result;
  4131. };
  4132. /**
  4133. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4134. * Returns the current Matrix.
  4135. */
  4136. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4137. var m = this.m;
  4138. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4139. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4140. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4141. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4142. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4143. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4144. 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);
  4145. return this;
  4146. };
  4147. // Statics
  4148. /**
  4149. * Returns a new Matrix set from the starting index of the passed array.
  4150. */
  4151. Matrix.FromArray = function (array, offset) {
  4152. var result = new Matrix();
  4153. if (!offset) {
  4154. offset = 0;
  4155. }
  4156. Matrix.FromArrayToRef(array, offset, result);
  4157. return result;
  4158. };
  4159. /**
  4160. * Sets the passed "result" matrix from the starting index of the passed array.
  4161. */
  4162. Matrix.FromArrayToRef = function (array, offset, result) {
  4163. for (var index = 0; index < 16; index++) {
  4164. result.m[index] = array[index + offset];
  4165. }
  4166. result._markAsUpdated();
  4167. };
  4168. /**
  4169. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4170. */
  4171. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4172. for (var index = 0; index < 16; index++) {
  4173. result.m[index] = array[index + offset] * scale;
  4174. }
  4175. result._markAsUpdated();
  4176. };
  4177. /**
  4178. * Sets the passed matrix "result" with the 16 passed floats.
  4179. */
  4180. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4181. result.m[0] = initialM11;
  4182. result.m[1] = initialM12;
  4183. result.m[2] = initialM13;
  4184. result.m[3] = initialM14;
  4185. result.m[4] = initialM21;
  4186. result.m[5] = initialM22;
  4187. result.m[6] = initialM23;
  4188. result.m[7] = initialM24;
  4189. result.m[8] = initialM31;
  4190. result.m[9] = initialM32;
  4191. result.m[10] = initialM33;
  4192. result.m[11] = initialM34;
  4193. result.m[12] = initialM41;
  4194. result.m[13] = initialM42;
  4195. result.m[14] = initialM43;
  4196. result.m[15] = initialM44;
  4197. result._markAsUpdated();
  4198. };
  4199. /**
  4200. * Returns the index-th row of the current matrix as a new Vector4.
  4201. */
  4202. Matrix.prototype.getRow = function (index) {
  4203. if (index < 0 || index > 3) {
  4204. return null;
  4205. }
  4206. var i = index * 4;
  4207. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4208. };
  4209. /**
  4210. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4211. * Returns the updated Matrix.
  4212. */
  4213. Matrix.prototype.setRow = function (index, row) {
  4214. if (index < 0 || index > 3) {
  4215. return this;
  4216. }
  4217. var i = index * 4;
  4218. this.m[i + 0] = row.x;
  4219. this.m[i + 1] = row.y;
  4220. this.m[i + 2] = row.z;
  4221. this.m[i + 3] = row.w;
  4222. this._markAsUpdated();
  4223. return this;
  4224. };
  4225. /**
  4226. * Compute the transpose of the matrix.
  4227. * Returns a new Matrix.
  4228. */
  4229. Matrix.prototype.transpose = function () {
  4230. return Matrix.Transpose(this);
  4231. };
  4232. /**
  4233. * Compute the transpose of the matrix.
  4234. * Returns the current matrix.
  4235. */
  4236. Matrix.prototype.transposeToRef = function (result) {
  4237. Matrix.TransposeToRef(this, result);
  4238. return this;
  4239. };
  4240. /**
  4241. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4242. * Returns the updated Matrix.
  4243. */
  4244. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4245. if (index < 0 || index > 3) {
  4246. return this;
  4247. }
  4248. var i = index * 4;
  4249. this.m[i + 0] = x;
  4250. this.m[i + 1] = y;
  4251. this.m[i + 2] = z;
  4252. this.m[i + 3] = w;
  4253. this._markAsUpdated();
  4254. return this;
  4255. };
  4256. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4257. /**
  4258. * Static identity matrix to be used as readonly matrix
  4259. * Must not be updated.
  4260. */
  4261. get: function () {
  4262. return Matrix._identityReadOnly;
  4263. },
  4264. enumerable: true,
  4265. configurable: true
  4266. });
  4267. /**
  4268. * Returns a new Matrix set from the 16 passed floats.
  4269. */
  4270. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4271. var result = new Matrix();
  4272. result.m[0] = initialM11;
  4273. result.m[1] = initialM12;
  4274. result.m[2] = initialM13;
  4275. result.m[3] = initialM14;
  4276. result.m[4] = initialM21;
  4277. result.m[5] = initialM22;
  4278. result.m[6] = initialM23;
  4279. result.m[7] = initialM24;
  4280. result.m[8] = initialM31;
  4281. result.m[9] = initialM32;
  4282. result.m[10] = initialM33;
  4283. result.m[11] = initialM34;
  4284. result.m[12] = initialM41;
  4285. result.m[13] = initialM42;
  4286. result.m[14] = initialM43;
  4287. result.m[15] = initialM44;
  4288. return result;
  4289. };
  4290. /**
  4291. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4292. */
  4293. Matrix.Compose = function (scale, rotation, translation) {
  4294. var result = Matrix.Identity();
  4295. Matrix.ComposeToRef(scale, rotation, translation, result);
  4296. return result;
  4297. };
  4298. /**
  4299. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4300. */
  4301. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4302. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4303. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4304. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4305. result.setTranslation(translation);
  4306. };
  4307. /**
  4308. * Returns a new indentity Matrix.
  4309. */
  4310. Matrix.Identity = function () {
  4311. 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);
  4312. };
  4313. /**
  4314. * Sets the passed "result" as an identity matrix.
  4315. */
  4316. Matrix.IdentityToRef = function (result) {
  4317. 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);
  4318. };
  4319. /**
  4320. * Returns a new zero Matrix.
  4321. */
  4322. Matrix.Zero = function () {
  4323. 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);
  4324. };
  4325. /**
  4326. * Returns a new rotation matrix for "angle" radians around the X axis.
  4327. */
  4328. Matrix.RotationX = function (angle) {
  4329. var result = new Matrix();
  4330. Matrix.RotationXToRef(angle, result);
  4331. return result;
  4332. };
  4333. /**
  4334. * Returns a new Matrix as the passed inverted one.
  4335. */
  4336. Matrix.Invert = function (source) {
  4337. var result = new Matrix();
  4338. source.invertToRef(result);
  4339. return result;
  4340. };
  4341. /**
  4342. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4343. */
  4344. Matrix.RotationXToRef = function (angle, result) {
  4345. var s = Math.sin(angle);
  4346. var c = Math.cos(angle);
  4347. result.m[0] = 1.0;
  4348. result.m[15] = 1.0;
  4349. result.m[5] = c;
  4350. result.m[10] = c;
  4351. result.m[9] = -s;
  4352. result.m[6] = s;
  4353. result.m[1] = 0.0;
  4354. result.m[2] = 0.0;
  4355. result.m[3] = 0.0;
  4356. result.m[4] = 0.0;
  4357. result.m[7] = 0.0;
  4358. result.m[8] = 0.0;
  4359. result.m[11] = 0.0;
  4360. result.m[12] = 0.0;
  4361. result.m[13] = 0.0;
  4362. result.m[14] = 0.0;
  4363. result._markAsUpdated();
  4364. };
  4365. /**
  4366. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4367. */
  4368. Matrix.RotationY = function (angle) {
  4369. var result = new Matrix();
  4370. Matrix.RotationYToRef(angle, result);
  4371. return result;
  4372. };
  4373. /**
  4374. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4375. */
  4376. Matrix.RotationYToRef = function (angle, result) {
  4377. var s = Math.sin(angle);
  4378. var c = Math.cos(angle);
  4379. result.m[5] = 1.0;
  4380. result.m[15] = 1.0;
  4381. result.m[0] = c;
  4382. result.m[2] = -s;
  4383. result.m[8] = s;
  4384. result.m[10] = c;
  4385. result.m[1] = 0.0;
  4386. result.m[3] = 0.0;
  4387. result.m[4] = 0.0;
  4388. result.m[6] = 0.0;
  4389. result.m[7] = 0.0;
  4390. result.m[9] = 0.0;
  4391. result.m[11] = 0.0;
  4392. result.m[12] = 0.0;
  4393. result.m[13] = 0.0;
  4394. result.m[14] = 0.0;
  4395. result._markAsUpdated();
  4396. };
  4397. /**
  4398. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4399. */
  4400. Matrix.RotationZ = function (angle) {
  4401. var result = new Matrix();
  4402. Matrix.RotationZToRef(angle, result);
  4403. return result;
  4404. };
  4405. /**
  4406. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4407. */
  4408. Matrix.RotationZToRef = function (angle, result) {
  4409. var s = Math.sin(angle);
  4410. var c = Math.cos(angle);
  4411. result.m[10] = 1.0;
  4412. result.m[15] = 1.0;
  4413. result.m[0] = c;
  4414. result.m[1] = s;
  4415. result.m[4] = -s;
  4416. result.m[5] = c;
  4417. result.m[2] = 0.0;
  4418. result.m[3] = 0.0;
  4419. result.m[6] = 0.0;
  4420. result.m[7] = 0.0;
  4421. result.m[8] = 0.0;
  4422. result.m[9] = 0.0;
  4423. result.m[11] = 0.0;
  4424. result.m[12] = 0.0;
  4425. result.m[13] = 0.0;
  4426. result.m[14] = 0.0;
  4427. result._markAsUpdated();
  4428. };
  4429. /**
  4430. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4431. */
  4432. Matrix.RotationAxis = function (axis, angle) {
  4433. var result = Matrix.Zero();
  4434. Matrix.RotationAxisToRef(axis, angle, result);
  4435. return result;
  4436. };
  4437. /**
  4438. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4439. */
  4440. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4441. var s = Math.sin(-angle);
  4442. var c = Math.cos(-angle);
  4443. var c1 = 1 - c;
  4444. axis.normalize();
  4445. result.m[0] = (axis.x * axis.x) * c1 + c;
  4446. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4447. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4448. result.m[3] = 0.0;
  4449. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4450. result.m[5] = (axis.y * axis.y) * c1 + c;
  4451. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4452. result.m[7] = 0.0;
  4453. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4454. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4455. result.m[10] = (axis.z * axis.z) * c1 + c;
  4456. result.m[11] = 0.0;
  4457. result.m[15] = 1.0;
  4458. result._markAsUpdated();
  4459. };
  4460. /**
  4461. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4462. */
  4463. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4464. var result = new Matrix();
  4465. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4466. return result;
  4467. };
  4468. /**
  4469. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4470. */
  4471. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4472. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4473. this._tempQuaternion.toRotationMatrix(result);
  4474. };
  4475. /**
  4476. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4477. */
  4478. Matrix.Scaling = function (x, y, z) {
  4479. var result = Matrix.Zero();
  4480. Matrix.ScalingToRef(x, y, z, result);
  4481. return result;
  4482. };
  4483. /**
  4484. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4485. */
  4486. Matrix.ScalingToRef = function (x, y, z, result) {
  4487. result.m[0] = x;
  4488. result.m[1] = 0.0;
  4489. result.m[2] = 0.0;
  4490. result.m[3] = 0.0;
  4491. result.m[4] = 0.0;
  4492. result.m[5] = y;
  4493. result.m[6] = 0.0;
  4494. result.m[7] = 0.0;
  4495. result.m[8] = 0.0;
  4496. result.m[9] = 0.0;
  4497. result.m[10] = z;
  4498. result.m[11] = 0.0;
  4499. result.m[12] = 0.0;
  4500. result.m[13] = 0.0;
  4501. result.m[14] = 0.0;
  4502. result.m[15] = 1.0;
  4503. result._markAsUpdated();
  4504. };
  4505. /**
  4506. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4507. */
  4508. Matrix.Translation = function (x, y, z) {
  4509. var result = Matrix.Identity();
  4510. Matrix.TranslationToRef(x, y, z, result);
  4511. return result;
  4512. };
  4513. /**
  4514. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4515. */
  4516. Matrix.TranslationToRef = function (x, y, z, result) {
  4517. 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);
  4518. };
  4519. /**
  4520. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4521. */
  4522. Matrix.Lerp = function (startValue, endValue, gradient) {
  4523. var result = Matrix.Zero();
  4524. for (var index = 0; index < 16; index++) {
  4525. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4526. }
  4527. result._markAsUpdated();
  4528. return result;
  4529. };
  4530. /**
  4531. * Returns a new Matrix whose values are computed by :
  4532. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4533. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4534. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4535. */
  4536. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4537. var startScale = new Vector3(0, 0, 0);
  4538. var startRotation = new Quaternion();
  4539. var startTranslation = new Vector3(0, 0, 0);
  4540. startValue.decompose(startScale, startRotation, startTranslation);
  4541. var endScale = new Vector3(0, 0, 0);
  4542. var endRotation = new Quaternion();
  4543. var endTranslation = new Vector3(0, 0, 0);
  4544. endValue.decompose(endScale, endRotation, endTranslation);
  4545. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4546. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4547. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4548. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4549. };
  4550. /**
  4551. * 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".
  4552. * This methods works for a Left-Handed system.
  4553. */
  4554. Matrix.LookAtLH = function (eye, target, up) {
  4555. var result = Matrix.Zero();
  4556. Matrix.LookAtLHToRef(eye, target, up, result);
  4557. return result;
  4558. };
  4559. /**
  4560. * 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".
  4561. * This methods works for a Left-Handed system.
  4562. */
  4563. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4564. // Z axis
  4565. target.subtractToRef(eye, this._zAxis);
  4566. this._zAxis.normalize();
  4567. // X axis
  4568. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4569. if (this._xAxis.lengthSquared() === 0) {
  4570. this._xAxis.x = 1.0;
  4571. }
  4572. else {
  4573. this._xAxis.normalize();
  4574. }
  4575. // Y axis
  4576. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4577. this._yAxis.normalize();
  4578. // Eye angles
  4579. var ex = -Vector3.Dot(this._xAxis, eye);
  4580. var ey = -Vector3.Dot(this._yAxis, eye);
  4581. var ez = -Vector3.Dot(this._zAxis, eye);
  4582. 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);
  4583. };
  4584. /**
  4585. * 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".
  4586. * This methods works for a Right-Handed system.
  4587. */
  4588. Matrix.LookAtRH = function (eye, target, up) {
  4589. var result = Matrix.Zero();
  4590. Matrix.LookAtRHToRef(eye, target, up, result);
  4591. return result;
  4592. };
  4593. /**
  4594. * 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".
  4595. * This methods works for a Left-Handed system.
  4596. */
  4597. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4598. // Z axis
  4599. eye.subtractToRef(target, this._zAxis);
  4600. this._zAxis.normalize();
  4601. // X axis
  4602. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4603. if (this._xAxis.lengthSquared() === 0) {
  4604. this._xAxis.x = 1.0;
  4605. }
  4606. else {
  4607. this._xAxis.normalize();
  4608. }
  4609. // Y axis
  4610. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4611. this._yAxis.normalize();
  4612. // Eye angles
  4613. var ex = -Vector3.Dot(this._xAxis, eye);
  4614. var ey = -Vector3.Dot(this._yAxis, eye);
  4615. var ez = -Vector3.Dot(this._zAxis, eye);
  4616. 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);
  4617. };
  4618. /**
  4619. * 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.
  4620. */
  4621. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4622. var matrix = Matrix.Zero();
  4623. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4624. return matrix;
  4625. };
  4626. /**
  4627. * 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.
  4628. */
  4629. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4630. var n = znear;
  4631. var f = zfar;
  4632. var a = 2.0 / width;
  4633. var b = 2.0 / height;
  4634. var c = 2.0 / (f - n);
  4635. var d = -(f + n) / (f - n);
  4636. 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);
  4637. };
  4638. /**
  4639. * 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.
  4640. */
  4641. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4642. var matrix = Matrix.Zero();
  4643. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4644. return matrix;
  4645. };
  4646. /**
  4647. * 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.
  4648. */
  4649. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4650. var n = znear;
  4651. var f = zfar;
  4652. var a = 2.0 / (right - left);
  4653. var b = 2.0 / (top - bottom);
  4654. var c = 2.0 / (f - n);
  4655. var d = -(f + n) / (f - n);
  4656. var i0 = (left + right) / (left - right);
  4657. var i1 = (top + bottom) / (bottom - top);
  4658. 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);
  4659. };
  4660. /**
  4661. * 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.
  4662. */
  4663. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4664. var matrix = Matrix.Zero();
  4665. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4666. return matrix;
  4667. };
  4668. /**
  4669. * 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.
  4670. */
  4671. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4672. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4673. result.m[10] *= -1.0;
  4674. };
  4675. /**
  4676. * 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.
  4677. */
  4678. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4679. var matrix = Matrix.Zero();
  4680. var n = znear;
  4681. var f = zfar;
  4682. var a = 2.0 * n / width;
  4683. var b = 2.0 * n / height;
  4684. var c = (f + n) / (f - n);
  4685. var d = -2.0 * f * n / (f - n);
  4686. 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);
  4687. return matrix;
  4688. };
  4689. /**
  4690. * 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.
  4691. */
  4692. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4693. var matrix = Matrix.Zero();
  4694. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4695. return matrix;
  4696. };
  4697. /**
  4698. * 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.
  4699. */
  4700. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4701. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4702. var n = znear;
  4703. var f = zfar;
  4704. var t = 1.0 / (Math.tan(fov * 0.5));
  4705. var a = isVerticalFovFixed ? (t / aspect) : t;
  4706. var b = isVerticalFovFixed ? t : (t * aspect);
  4707. var c = (f + n) / (f - n);
  4708. var d = -2.0 * f * n / (f - n);
  4709. 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);
  4710. };
  4711. /**
  4712. * 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.
  4713. */
  4714. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4715. var matrix = Matrix.Zero();
  4716. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4717. return matrix;
  4718. };
  4719. /**
  4720. * 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.
  4721. */
  4722. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4723. //alternatively this could be expressed as:
  4724. // m = PerspectiveFovLHToRef
  4725. // m[10] *= -1.0;
  4726. // m[11] *= -1.0;
  4727. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4728. var n = znear;
  4729. var f = zfar;
  4730. var t = 1.0 / (Math.tan(fov * 0.5));
  4731. var a = isVerticalFovFixed ? (t / aspect) : t;
  4732. var b = isVerticalFovFixed ? t : (t * aspect);
  4733. var c = -(f + n) / (f - n);
  4734. var d = -2 * f * n / (f - n);
  4735. 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);
  4736. };
  4737. /**
  4738. * 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.
  4739. */
  4740. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4741. if (rightHanded === void 0) { rightHanded = false; }
  4742. var rightHandedFactor = rightHanded ? -1 : 1;
  4743. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4744. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4745. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4746. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4747. var xScale = 2.0 / (leftTan + rightTan);
  4748. var yScale = 2.0 / (upTan + downTan);
  4749. result.m[0] = xScale;
  4750. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4751. result.m[5] = yScale;
  4752. result.m[6] = result.m[7] = 0.0;
  4753. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4754. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4755. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4756. result.m[10] = -zfar / (znear - zfar);
  4757. result.m[11] = 1.0 * rightHandedFactor;
  4758. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4759. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4760. // result.m[14] = (znear * zfar) / (znear - zfar);
  4761. result._markAsUpdated();
  4762. };
  4763. /**
  4764. * Returns the final transformation matrix : world * view * projection * viewport
  4765. */
  4766. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  4767. var cw = viewport.width;
  4768. var ch = viewport.height;
  4769. var cx = viewport.x;
  4770. var cy = viewport.y;
  4771. 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);
  4772. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  4773. };
  4774. /**
  4775. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  4776. */
  4777. Matrix.GetAsMatrix2x2 = function (matrix) {
  4778. return new Float32Array([
  4779. matrix.m[0], matrix.m[1],
  4780. matrix.m[4], matrix.m[5]
  4781. ]);
  4782. };
  4783. /**
  4784. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  4785. */
  4786. Matrix.GetAsMatrix3x3 = function (matrix) {
  4787. return new Float32Array([
  4788. matrix.m[0], matrix.m[1], matrix.m[2],
  4789. matrix.m[4], matrix.m[5], matrix.m[6],
  4790. matrix.m[8], matrix.m[9], matrix.m[10]
  4791. ]);
  4792. };
  4793. /**
  4794. * Compute the transpose of the passed Matrix.
  4795. * Returns a new Matrix.
  4796. */
  4797. Matrix.Transpose = function (matrix) {
  4798. var result = new Matrix();
  4799. Matrix.TransposeToRef(matrix, result);
  4800. return result;
  4801. };
  4802. /**
  4803. * Compute the transpose of the passed Matrix and store it in the result matrix.
  4804. */
  4805. Matrix.TransposeToRef = function (matrix, result) {
  4806. result.m[0] = matrix.m[0];
  4807. result.m[1] = matrix.m[4];
  4808. result.m[2] = matrix.m[8];
  4809. result.m[3] = matrix.m[12];
  4810. result.m[4] = matrix.m[1];
  4811. result.m[5] = matrix.m[5];
  4812. result.m[6] = matrix.m[9];
  4813. result.m[7] = matrix.m[13];
  4814. result.m[8] = matrix.m[2];
  4815. result.m[9] = matrix.m[6];
  4816. result.m[10] = matrix.m[10];
  4817. result.m[11] = matrix.m[14];
  4818. result.m[12] = matrix.m[3];
  4819. result.m[13] = matrix.m[7];
  4820. result.m[14] = matrix.m[11];
  4821. result.m[15] = matrix.m[15];
  4822. };
  4823. /**
  4824. * Returns a new Matrix as the reflection matrix across the passed plane.
  4825. */
  4826. Matrix.Reflection = function (plane) {
  4827. var matrix = new Matrix();
  4828. Matrix.ReflectionToRef(plane, matrix);
  4829. return matrix;
  4830. };
  4831. /**
  4832. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  4833. */
  4834. Matrix.ReflectionToRef = function (plane, result) {
  4835. plane.normalize();
  4836. var x = plane.normal.x;
  4837. var y = plane.normal.y;
  4838. var z = plane.normal.z;
  4839. var temp = -2 * x;
  4840. var temp2 = -2 * y;
  4841. var temp3 = -2 * z;
  4842. result.m[0] = (temp * x) + 1;
  4843. result.m[1] = temp2 * x;
  4844. result.m[2] = temp3 * x;
  4845. result.m[3] = 0.0;
  4846. result.m[4] = temp * y;
  4847. result.m[5] = (temp2 * y) + 1;
  4848. result.m[6] = temp3 * y;
  4849. result.m[7] = 0.0;
  4850. result.m[8] = temp * z;
  4851. result.m[9] = temp2 * z;
  4852. result.m[10] = (temp3 * z) + 1;
  4853. result.m[11] = 0.0;
  4854. result.m[12] = temp * plane.d;
  4855. result.m[13] = temp2 * plane.d;
  4856. result.m[14] = temp3 * plane.d;
  4857. result.m[15] = 1.0;
  4858. result._markAsUpdated();
  4859. };
  4860. /**
  4861. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4862. */
  4863. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4864. result.m[0] = xaxis.x;
  4865. result.m[1] = xaxis.y;
  4866. result.m[2] = xaxis.z;
  4867. result.m[3] = 0.0;
  4868. result.m[4] = yaxis.x;
  4869. result.m[5] = yaxis.y;
  4870. result.m[6] = yaxis.z;
  4871. result.m[7] = 0.0;
  4872. result.m[8] = zaxis.x;
  4873. result.m[9] = zaxis.y;
  4874. result.m[10] = zaxis.z;
  4875. result.m[11] = 0.0;
  4876. result.m[12] = 0.0;
  4877. result.m[13] = 0.0;
  4878. result.m[14] = 0.0;
  4879. result.m[15] = 1.0;
  4880. result._markAsUpdated();
  4881. };
  4882. /**
  4883. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4884. */
  4885. Matrix.FromQuaternionToRef = function (quat, result) {
  4886. var xx = quat.x * quat.x;
  4887. var yy = quat.y * quat.y;
  4888. var zz = quat.z * quat.z;
  4889. var xy = quat.x * quat.y;
  4890. var zw = quat.z * quat.w;
  4891. var zx = quat.z * quat.x;
  4892. var yw = quat.y * quat.w;
  4893. var yz = quat.y * quat.z;
  4894. var xw = quat.x * quat.w;
  4895. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4896. result.m[1] = 2.0 * (xy + zw);
  4897. result.m[2] = 2.0 * (zx - yw);
  4898. result.m[3] = 0.0;
  4899. result.m[4] = 2.0 * (xy - zw);
  4900. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4901. result.m[6] = 2.0 * (yz + xw);
  4902. result.m[7] = 0.0;
  4903. result.m[8] = 2.0 * (zx + yw);
  4904. result.m[9] = 2.0 * (yz - xw);
  4905. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4906. result.m[11] = 0.0;
  4907. result.m[12] = 0.0;
  4908. result.m[13] = 0.0;
  4909. result.m[14] = 0.0;
  4910. result.m[15] = 1.0;
  4911. result._markAsUpdated();
  4912. };
  4913. Matrix._tempQuaternion = new Quaternion();
  4914. Matrix._xAxis = Vector3.Zero();
  4915. Matrix._yAxis = Vector3.Zero();
  4916. Matrix._zAxis = Vector3.Zero();
  4917. Matrix._updateFlagSeed = 0;
  4918. Matrix._identityReadOnly = Matrix.Identity();
  4919. return Matrix;
  4920. }());
  4921. BABYLON.Matrix = Matrix;
  4922. var Plane = /** @class */ (function () {
  4923. /**
  4924. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4925. */
  4926. function Plane(a, b, c, d) {
  4927. this.normal = new Vector3(a, b, c);
  4928. this.d = d;
  4929. }
  4930. /**
  4931. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4932. */
  4933. Plane.prototype.asArray = function () {
  4934. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4935. };
  4936. // Methods
  4937. /**
  4938. * Returns a new plane copied from the current Plane.
  4939. */
  4940. Plane.prototype.clone = function () {
  4941. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4942. };
  4943. /**
  4944. * Returns the string "Plane".
  4945. */
  4946. Plane.prototype.getClassName = function () {
  4947. return "Plane";
  4948. };
  4949. /**
  4950. * Returns the Plane hash code.
  4951. */
  4952. Plane.prototype.getHashCode = function () {
  4953. var hash = this.normal.getHashCode();
  4954. hash = (hash * 397) ^ (this.d || 0);
  4955. return hash;
  4956. };
  4957. /**
  4958. * Normalize the current Plane in place.
  4959. * Returns the updated Plane.
  4960. */
  4961. Plane.prototype.normalize = function () {
  4962. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4963. var magnitude = 0.0;
  4964. if (norm !== 0) {
  4965. magnitude = 1.0 / norm;
  4966. }
  4967. this.normal.x *= magnitude;
  4968. this.normal.y *= magnitude;
  4969. this.normal.z *= magnitude;
  4970. this.d *= magnitude;
  4971. return this;
  4972. };
  4973. /**
  4974. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4975. */
  4976. Plane.prototype.transform = function (transformation) {
  4977. var transposedMatrix = Matrix.Transpose(transformation);
  4978. var x = this.normal.x;
  4979. var y = this.normal.y;
  4980. var z = this.normal.z;
  4981. var d = this.d;
  4982. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4983. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4984. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4985. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4986. return new Plane(normalX, normalY, normalZ, finalD);
  4987. };
  4988. /**
  4989. * Returns the dot product (float) of the point coordinates and the plane normal.
  4990. */
  4991. Plane.prototype.dotCoordinate = function (point) {
  4992. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4993. };
  4994. /**
  4995. * Updates the current Plane from the plane defined by the three passed points.
  4996. * Returns the updated Plane.
  4997. */
  4998. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4999. var x1 = point2.x - point1.x;
  5000. var y1 = point2.y - point1.y;
  5001. var z1 = point2.z - point1.z;
  5002. var x2 = point3.x - point1.x;
  5003. var y2 = point3.y - point1.y;
  5004. var z2 = point3.z - point1.z;
  5005. var yz = (y1 * z2) - (z1 * y2);
  5006. var xz = (z1 * x2) - (x1 * z2);
  5007. var xy = (x1 * y2) - (y1 * x2);
  5008. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5009. var invPyth;
  5010. if (pyth !== 0) {
  5011. invPyth = 1.0 / pyth;
  5012. }
  5013. else {
  5014. invPyth = 0.0;
  5015. }
  5016. this.normal.x = yz * invPyth;
  5017. this.normal.y = xz * invPyth;
  5018. this.normal.z = xy * invPyth;
  5019. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5020. return this;
  5021. };
  5022. /**
  5023. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5024. */
  5025. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5026. var dot = Vector3.Dot(this.normal, direction);
  5027. return (dot <= epsilon);
  5028. };
  5029. /**
  5030. * Returns the signed distance (float) from the passed point to the Plane.
  5031. */
  5032. Plane.prototype.signedDistanceTo = function (point) {
  5033. return Vector3.Dot(point, this.normal) + this.d;
  5034. };
  5035. // Statics
  5036. /**
  5037. * Returns a new Plane from the passed array.
  5038. */
  5039. Plane.FromArray = function (array) {
  5040. return new Plane(array[0], array[1], array[2], array[3]);
  5041. };
  5042. /**
  5043. * Returns a new Plane defined by the three passed points.
  5044. */
  5045. Plane.FromPoints = function (point1, point2, point3) {
  5046. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5047. result.copyFromPoints(point1, point2, point3);
  5048. return result;
  5049. };
  5050. /**
  5051. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5052. * Note : the vector "normal" is updated because normalized.
  5053. */
  5054. Plane.FromPositionAndNormal = function (origin, normal) {
  5055. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5056. normal.normalize();
  5057. result.normal = normal;
  5058. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5059. return result;
  5060. };
  5061. /**
  5062. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5063. */
  5064. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5065. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5066. return Vector3.Dot(point, normal) + d;
  5067. };
  5068. return Plane;
  5069. }());
  5070. BABYLON.Plane = Plane;
  5071. var Viewport = /** @class */ (function () {
  5072. /**
  5073. * Creates a Viewport object located at (x, y) and sized (width, height).
  5074. */
  5075. function Viewport(x, y, width, height) {
  5076. this.x = x;
  5077. this.y = y;
  5078. this.width = width;
  5079. this.height = height;
  5080. }
  5081. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5082. if (renderWidthOrEngine.getRenderWidth) {
  5083. var engine = renderWidthOrEngine;
  5084. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5085. }
  5086. var renderWidth = renderWidthOrEngine;
  5087. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5088. };
  5089. /**
  5090. * Returns a new Viewport copied from the current one.
  5091. */
  5092. Viewport.prototype.clone = function () {
  5093. return new Viewport(this.x, this.y, this.width, this.height);
  5094. };
  5095. return Viewport;
  5096. }());
  5097. BABYLON.Viewport = Viewport;
  5098. var Frustum = /** @class */ (function () {
  5099. function Frustum() {
  5100. }
  5101. /**
  5102. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5103. */
  5104. Frustum.GetPlanes = function (transform) {
  5105. var frustumPlanes = [];
  5106. for (var index = 0; index < 6; index++) {
  5107. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5108. }
  5109. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5110. return frustumPlanes;
  5111. };
  5112. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5113. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5114. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5115. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5116. frustumPlane.d = transform.m[15] + transform.m[14];
  5117. frustumPlane.normalize();
  5118. };
  5119. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5120. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5121. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5122. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5123. frustumPlane.d = transform.m[15] - transform.m[14];
  5124. frustumPlane.normalize();
  5125. };
  5126. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5127. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5128. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5129. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5130. frustumPlane.d = transform.m[15] + transform.m[12];
  5131. frustumPlane.normalize();
  5132. };
  5133. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5134. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5135. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5136. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5137. frustumPlane.d = transform.m[15] - transform.m[12];
  5138. frustumPlane.normalize();
  5139. };
  5140. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5141. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5142. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5143. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5144. frustumPlane.d = transform.m[15] - transform.m[13];
  5145. frustumPlane.normalize();
  5146. };
  5147. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5148. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5149. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5150. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5151. frustumPlane.d = transform.m[15] + transform.m[13];
  5152. frustumPlane.normalize();
  5153. };
  5154. /**
  5155. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5156. */
  5157. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5158. // Near
  5159. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5160. // Far
  5161. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5162. // Left
  5163. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5164. // Right
  5165. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5166. // Top
  5167. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5168. // Bottom
  5169. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5170. };
  5171. return Frustum;
  5172. }());
  5173. BABYLON.Frustum = Frustum;
  5174. var Space;
  5175. (function (Space) {
  5176. Space[Space["LOCAL"] = 0] = "LOCAL";
  5177. Space[Space["WORLD"] = 1] = "WORLD";
  5178. Space[Space["BONE"] = 2] = "BONE";
  5179. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5180. var Axis = /** @class */ (function () {
  5181. function Axis() {
  5182. }
  5183. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5184. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5185. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5186. return Axis;
  5187. }());
  5188. BABYLON.Axis = Axis;
  5189. ;
  5190. var BezierCurve = /** @class */ (function () {
  5191. function BezierCurve() {
  5192. }
  5193. /**
  5194. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5195. */
  5196. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5197. // Extract X (which is equal to time here)
  5198. var f0 = 1 - 3 * x2 + 3 * x1;
  5199. var f1 = 3 * x2 - 6 * x1;
  5200. var f2 = 3 * x1;
  5201. var refinedT = t;
  5202. for (var i = 0; i < 5; i++) {
  5203. var refinedT2 = refinedT * refinedT;
  5204. var refinedT3 = refinedT2 * refinedT;
  5205. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5206. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5207. refinedT -= (x - t) * slope;
  5208. refinedT = Math.min(1, Math.max(0, refinedT));
  5209. }
  5210. // Resolve cubic bezier for the given x
  5211. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5212. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5213. Math.pow(refinedT, 3);
  5214. };
  5215. return BezierCurve;
  5216. }());
  5217. BABYLON.BezierCurve = BezierCurve;
  5218. var Orientation;
  5219. (function (Orientation) {
  5220. Orientation[Orientation["CW"] = 0] = "CW";
  5221. Orientation[Orientation["CCW"] = 1] = "CCW";
  5222. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5223. var Angle = /** @class */ (function () {
  5224. /**
  5225. * Creates an Angle object of "radians" radians (float).
  5226. */
  5227. function Angle(radians) {
  5228. var _this = this;
  5229. /**
  5230. * Returns the Angle value in degrees (float).
  5231. */
  5232. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5233. /**
  5234. * Returns the Angle value in radians (float).
  5235. */
  5236. this.radians = function () { return _this._radians; };
  5237. this._radians = radians;
  5238. if (this._radians < 0.0)
  5239. this._radians += (2.0 * Math.PI);
  5240. }
  5241. /**
  5242. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5243. */
  5244. Angle.BetweenTwoPoints = function (a, b) {
  5245. var delta = b.subtract(a);
  5246. var theta = Math.atan2(delta.y, delta.x);
  5247. return new Angle(theta);
  5248. };
  5249. /**
  5250. * Returns a new Angle object from the passed float in radians.
  5251. */
  5252. Angle.FromRadians = function (radians) {
  5253. return new Angle(radians);
  5254. };
  5255. /**
  5256. * Returns a new Angle object from the passed float in degrees.
  5257. */
  5258. Angle.FromDegrees = function (degrees) {
  5259. return new Angle(degrees * Math.PI / 180.0);
  5260. };
  5261. return Angle;
  5262. }());
  5263. BABYLON.Angle = Angle;
  5264. var Arc2 = /** @class */ (function () {
  5265. /**
  5266. * Creates an Arc object from the three passed points : start, middle and end.
  5267. */
  5268. function Arc2(startPoint, midPoint, endPoint) {
  5269. this.startPoint = startPoint;
  5270. this.midPoint = midPoint;
  5271. this.endPoint = endPoint;
  5272. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5273. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5274. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5275. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5276. 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);
  5277. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5278. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5279. var a1 = this.startAngle.degrees();
  5280. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5281. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5282. // angles correction
  5283. if (a2 - a1 > +180.0)
  5284. a2 -= 360.0;
  5285. if (a2 - a1 < -180.0)
  5286. a2 += 360.0;
  5287. if (a3 - a2 > +180.0)
  5288. a3 -= 360.0;
  5289. if (a3 - a2 < -180.0)
  5290. a3 += 360.0;
  5291. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5292. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5293. }
  5294. return Arc2;
  5295. }());
  5296. BABYLON.Arc2 = Arc2;
  5297. var Path2 = /** @class */ (function () {
  5298. /**
  5299. * Creates a Path2 object from the starting 2D coordinates x and y.
  5300. */
  5301. function Path2(x, y) {
  5302. this._points = new Array();
  5303. this._length = 0.0;
  5304. this.closed = false;
  5305. this._points.push(new Vector2(x, y));
  5306. }
  5307. /**
  5308. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5309. * Returns the updated Path2.
  5310. */
  5311. Path2.prototype.addLineTo = function (x, y) {
  5312. if (this.closed) {
  5313. //Tools.Error("cannot add lines to closed paths");
  5314. return this;
  5315. }
  5316. var newPoint = new Vector2(x, y);
  5317. var previousPoint = this._points[this._points.length - 1];
  5318. this._points.push(newPoint);
  5319. this._length += newPoint.subtract(previousPoint).length();
  5320. return this;
  5321. };
  5322. /**
  5323. * 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.
  5324. * Returns the updated Path2.
  5325. */
  5326. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5327. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5328. if (this.closed) {
  5329. //Tools.Error("cannot add arcs to closed paths");
  5330. return this;
  5331. }
  5332. var startPoint = this._points[this._points.length - 1];
  5333. var midPoint = new Vector2(midX, midY);
  5334. var endPoint = new Vector2(endX, endY);
  5335. var arc = new Arc2(startPoint, midPoint, endPoint);
  5336. var increment = arc.angle.radians() / numberOfSegments;
  5337. if (arc.orientation === Orientation.CW)
  5338. increment *= -1;
  5339. var currentAngle = arc.startAngle.radians() + increment;
  5340. for (var i = 0; i < numberOfSegments; i++) {
  5341. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5342. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5343. this.addLineTo(x, y);
  5344. currentAngle += increment;
  5345. }
  5346. return this;
  5347. };
  5348. /**
  5349. * Closes the Path2.
  5350. * Returns the Path2.
  5351. */
  5352. Path2.prototype.close = function () {
  5353. this.closed = true;
  5354. return this;
  5355. };
  5356. /**
  5357. * Returns the Path2 total length (float).
  5358. */
  5359. Path2.prototype.length = function () {
  5360. var result = this._length;
  5361. if (!this.closed) {
  5362. var lastPoint = this._points[this._points.length - 1];
  5363. var firstPoint = this._points[0];
  5364. result += (firstPoint.subtract(lastPoint).length());
  5365. }
  5366. return result;
  5367. };
  5368. /**
  5369. * Returns the Path2 internal array of points.
  5370. */
  5371. Path2.prototype.getPoints = function () {
  5372. return this._points;
  5373. };
  5374. /**
  5375. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5376. */
  5377. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5378. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5379. //Tools.Error("normalized length position should be between 0 and 1.");
  5380. return Vector2.Zero();
  5381. }
  5382. var lengthPosition = normalizedLengthPosition * this.length();
  5383. var previousOffset = 0;
  5384. for (var i = 0; i < this._points.length; i++) {
  5385. var j = (i + 1) % this._points.length;
  5386. var a = this._points[i];
  5387. var b = this._points[j];
  5388. var bToA = b.subtract(a);
  5389. var nextOffset = (bToA.length() + previousOffset);
  5390. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5391. var dir = bToA.normalize();
  5392. var localOffset = lengthPosition - previousOffset;
  5393. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5394. }
  5395. previousOffset = nextOffset;
  5396. }
  5397. //Tools.Error("internal error");
  5398. return Vector2.Zero();
  5399. };
  5400. /**
  5401. * Returns a new Path2 starting at the coordinates (x, y).
  5402. */
  5403. Path2.StartingAt = function (x, y) {
  5404. return new Path2(x, y);
  5405. };
  5406. return Path2;
  5407. }());
  5408. BABYLON.Path2 = Path2;
  5409. var Path3D = /** @class */ (function () {
  5410. /**
  5411. * new Path3D(path, normal, raw)
  5412. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5413. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5414. * path : an array of Vector3, the curve axis of the Path3D
  5415. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5416. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5417. */
  5418. function Path3D(path, firstNormal, raw) {
  5419. if (firstNormal === void 0) { firstNormal = null; }
  5420. this.path = path;
  5421. this._curve = new Array();
  5422. this._distances = new Array();
  5423. this._tangents = new Array();
  5424. this._normals = new Array();
  5425. this._binormals = new Array();
  5426. for (var p = 0; p < path.length; p++) {
  5427. this._curve[p] = path[p].clone(); // hard copy
  5428. }
  5429. this._raw = raw || false;
  5430. this._compute(firstNormal);
  5431. }
  5432. /**
  5433. * Returns the Path3D array of successive Vector3 designing its curve.
  5434. */
  5435. Path3D.prototype.getCurve = function () {
  5436. return this._curve;
  5437. };
  5438. /**
  5439. * Returns an array populated with tangent vectors on each Path3D curve point.
  5440. */
  5441. Path3D.prototype.getTangents = function () {
  5442. return this._tangents;
  5443. };
  5444. /**
  5445. * Returns an array populated with normal vectors on each Path3D curve point.
  5446. */
  5447. Path3D.prototype.getNormals = function () {
  5448. return this._normals;
  5449. };
  5450. /**
  5451. * Returns an array populated with binormal vectors on each Path3D curve point.
  5452. */
  5453. Path3D.prototype.getBinormals = function () {
  5454. return this._binormals;
  5455. };
  5456. /**
  5457. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5458. */
  5459. Path3D.prototype.getDistances = function () {
  5460. return this._distances;
  5461. };
  5462. /**
  5463. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5464. * Returns the same object updated.
  5465. */
  5466. Path3D.prototype.update = function (path, firstNormal) {
  5467. if (firstNormal === void 0) { firstNormal = null; }
  5468. for (var p = 0; p < path.length; p++) {
  5469. this._curve[p].x = path[p].x;
  5470. this._curve[p].y = path[p].y;
  5471. this._curve[p].z = path[p].z;
  5472. }
  5473. this._compute(firstNormal);
  5474. return this;
  5475. };
  5476. // private function compute() : computes tangents, normals and binormals
  5477. Path3D.prototype._compute = function (firstNormal) {
  5478. var l = this._curve.length;
  5479. // first and last tangents
  5480. this._tangents[0] = this._getFirstNonNullVector(0);
  5481. if (!this._raw) {
  5482. this._tangents[0].normalize();
  5483. }
  5484. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5485. if (!this._raw) {
  5486. this._tangents[l - 1].normalize();
  5487. }
  5488. // normals and binormals at first point : arbitrary vector with _normalVector()
  5489. var tg0 = this._tangents[0];
  5490. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5491. this._normals[0] = pp0;
  5492. if (!this._raw) {
  5493. this._normals[0].normalize();
  5494. }
  5495. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5496. if (!this._raw) {
  5497. this._binormals[0].normalize();
  5498. }
  5499. this._distances[0] = 0.0;
  5500. // normals and binormals : next points
  5501. var prev; // previous vector (segment)
  5502. var cur; // current vector (segment)
  5503. var curTang; // current tangent
  5504. // previous normal
  5505. var prevBinor; // previous binormal
  5506. for (var i = 1; i < l; i++) {
  5507. // tangents
  5508. prev = this._getLastNonNullVector(i);
  5509. if (i < l - 1) {
  5510. cur = this._getFirstNonNullVector(i);
  5511. this._tangents[i] = prev.add(cur);
  5512. this._tangents[i].normalize();
  5513. }
  5514. this._distances[i] = this._distances[i - 1] + prev.length();
  5515. // normals and binormals
  5516. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5517. curTang = this._tangents[i];
  5518. prevBinor = this._binormals[i - 1];
  5519. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5520. if (!this._raw) {
  5521. this._normals[i].normalize();
  5522. }
  5523. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5524. if (!this._raw) {
  5525. this._binormals[i].normalize();
  5526. }
  5527. }
  5528. };
  5529. // private function getFirstNonNullVector(index)
  5530. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5531. Path3D.prototype._getFirstNonNullVector = function (index) {
  5532. var i = 1;
  5533. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5534. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5535. i++;
  5536. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5537. }
  5538. return nNVector;
  5539. };
  5540. // private function getLastNonNullVector(index)
  5541. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5542. Path3D.prototype._getLastNonNullVector = function (index) {
  5543. var i = 1;
  5544. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5545. while (nLVector.length() === 0 && index > i + 1) {
  5546. i++;
  5547. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5548. }
  5549. return nLVector;
  5550. };
  5551. // private function normalVector(v0, vt, va) :
  5552. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5553. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5554. Path3D.prototype._normalVector = function (v0, vt, va) {
  5555. var normal0;
  5556. var tgl = vt.length();
  5557. if (tgl === 0.0) {
  5558. tgl = 1.0;
  5559. }
  5560. if (va === undefined || va === null) {
  5561. var point;
  5562. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5563. point = new Vector3(0.0, -1.0, 0.0);
  5564. }
  5565. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5566. point = new Vector3(1.0, 0.0, 0.0);
  5567. }
  5568. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5569. point = new Vector3(0.0, 0.0, 1.0);
  5570. }
  5571. else {
  5572. point = Vector3.Zero();
  5573. }
  5574. normal0 = Vector3.Cross(vt, point);
  5575. }
  5576. else {
  5577. normal0 = Vector3.Cross(vt, va);
  5578. Vector3.CrossToRef(normal0, vt, normal0);
  5579. }
  5580. normal0.normalize();
  5581. return normal0;
  5582. };
  5583. return Path3D;
  5584. }());
  5585. BABYLON.Path3D = Path3D;
  5586. var Curve3 = /** @class */ (function () {
  5587. /**
  5588. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5589. * A Curve3 is designed from a series of successive Vector3.
  5590. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5591. */
  5592. function Curve3(points) {
  5593. this._length = 0.0;
  5594. this._points = points;
  5595. this._length = this._computeLength(points);
  5596. }
  5597. /**
  5598. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5599. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5600. * @param v1 (Vector3) the control point
  5601. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5602. * @param nbPoints (integer) the wanted number of points in the curve
  5603. */
  5604. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5605. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5606. var bez = new Array();
  5607. var equation = function (t, val0, val1, val2) {
  5608. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5609. return res;
  5610. };
  5611. for (var i = 0; i <= nbPoints; i++) {
  5612. 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)));
  5613. }
  5614. return new Curve3(bez);
  5615. };
  5616. /**
  5617. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5618. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5619. * @param v1 (Vector3) the first control point
  5620. * @param v2 (Vector3) the second control point
  5621. * @param v3 (Vector3) the end point of the Cubic Bezier
  5622. * @param nbPoints (integer) the wanted number of points in the curve
  5623. */
  5624. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5625. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5626. var bez = new Array();
  5627. var equation = function (t, val0, val1, val2, val3) {
  5628. 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;
  5629. return res;
  5630. };
  5631. for (var i = 0; i <= nbPoints; i++) {
  5632. 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)));
  5633. }
  5634. return new Curve3(bez);
  5635. };
  5636. /**
  5637. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5638. * @param p1 (Vector3) the origin point of the Hermite Spline
  5639. * @param t1 (Vector3) the tangent vector at the origin point
  5640. * @param p2 (Vector3) the end point of the Hermite Spline
  5641. * @param t2 (Vector3) the tangent vector at the end point
  5642. * @param nbPoints (integer) the wanted number of points in the curve
  5643. */
  5644. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5645. var hermite = new Array();
  5646. var step = 1.0 / nbPoints;
  5647. for (var i = 0; i <= nbPoints; i++) {
  5648. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5649. }
  5650. return new Curve3(hermite);
  5651. };
  5652. /**
  5653. * Returns a Curve3 object along a CatmullRom Spline curve :
  5654. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5655. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5656. */
  5657. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5658. var totalPoints = new Array();
  5659. totalPoints.push(points[0].clone());
  5660. Array.prototype.push.apply(totalPoints, points);
  5661. totalPoints.push(points[points.length - 1].clone());
  5662. var catmullRom = new Array();
  5663. var step = 1.0 / nbPoints;
  5664. var amount = 0.0;
  5665. for (var i = 0; i < totalPoints.length - 3; i++) {
  5666. amount = 0;
  5667. for (var c = 0; c < nbPoints; c++) {
  5668. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5669. amount += step;
  5670. }
  5671. }
  5672. i--;
  5673. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5674. return new Curve3(catmullRom);
  5675. };
  5676. /**
  5677. * Returns the Curve3 stored array of successive Vector3
  5678. */
  5679. Curve3.prototype.getPoints = function () {
  5680. return this._points;
  5681. };
  5682. /**
  5683. * Returns the computed length (float) of the curve.
  5684. */
  5685. Curve3.prototype.length = function () {
  5686. return this._length;
  5687. };
  5688. /**
  5689. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5690. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5691. * curveA and curveB keep unchanged.
  5692. */
  5693. Curve3.prototype.continue = function (curve) {
  5694. var lastPoint = this._points[this._points.length - 1];
  5695. var continuedPoints = this._points.slice();
  5696. var curvePoints = curve.getPoints();
  5697. for (var i = 1; i < curvePoints.length; i++) {
  5698. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5699. }
  5700. var continuedCurve = new Curve3(continuedPoints);
  5701. return continuedCurve;
  5702. };
  5703. Curve3.prototype._computeLength = function (path) {
  5704. var l = 0;
  5705. for (var i = 1; i < path.length; i++) {
  5706. l += (path[i].subtract(path[i - 1])).length();
  5707. }
  5708. return l;
  5709. };
  5710. return Curve3;
  5711. }());
  5712. BABYLON.Curve3 = Curve3;
  5713. // Vertex formats
  5714. var PositionNormalVertex = /** @class */ (function () {
  5715. function PositionNormalVertex(position, normal) {
  5716. if (position === void 0) { position = Vector3.Zero(); }
  5717. if (normal === void 0) { normal = Vector3.Up(); }
  5718. this.position = position;
  5719. this.normal = normal;
  5720. }
  5721. PositionNormalVertex.prototype.clone = function () {
  5722. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5723. };
  5724. return PositionNormalVertex;
  5725. }());
  5726. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5727. var PositionNormalTextureVertex = /** @class */ (function () {
  5728. function PositionNormalTextureVertex(position, normal, uv) {
  5729. if (position === void 0) { position = Vector3.Zero(); }
  5730. if (normal === void 0) { normal = Vector3.Up(); }
  5731. if (uv === void 0) { uv = Vector2.Zero(); }
  5732. this.position = position;
  5733. this.normal = normal;
  5734. this.uv = uv;
  5735. }
  5736. PositionNormalTextureVertex.prototype.clone = function () {
  5737. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5738. };
  5739. return PositionNormalTextureVertex;
  5740. }());
  5741. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5742. // Temporary pre-allocated objects for engine internal use
  5743. // usage in any internal function :
  5744. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5745. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5746. var Tmp = /** @class */ (function () {
  5747. function Tmp() {
  5748. }
  5749. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5750. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5751. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5752. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5753. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5754. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5755. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5756. Matrix.Zero(), Matrix.Zero(),
  5757. Matrix.Zero(), Matrix.Zero(),
  5758. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5759. return Tmp;
  5760. }());
  5761. BABYLON.Tmp = Tmp;
  5762. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5763. var MathTmp = /** @class */ (function () {
  5764. function MathTmp() {
  5765. }
  5766. MathTmp.Vector3 = [Vector3.Zero()];
  5767. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  5768. MathTmp.Quaternion = [Quaternion.Zero()];
  5769. return MathTmp;
  5770. }());
  5771. })(BABYLON || (BABYLON = {}));
  5772. //# sourceMappingURL=babylon.math.js.map
  5773. var BABYLON;
  5774. (function (BABYLON) {
  5775. var Scalar = /** @class */ (function () {
  5776. function Scalar() {
  5777. }
  5778. /**
  5779. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  5780. */
  5781. Scalar.WithinEpsilon = function (a, b, epsilon) {
  5782. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  5783. var num = a - b;
  5784. return -epsilon <= num && num <= epsilon;
  5785. };
  5786. /**
  5787. * Returns a string : the upper case translation of the number i to hexadecimal.
  5788. */
  5789. Scalar.ToHex = function (i) {
  5790. var str = i.toString(16);
  5791. if (i <= 15) {
  5792. return ("0" + str).toUpperCase();
  5793. }
  5794. return str.toUpperCase();
  5795. };
  5796. /**
  5797. * Returns -1 if value is negative and +1 is value is positive.
  5798. * Returns the value itself if it's equal to zero.
  5799. */
  5800. Scalar.Sign = function (value) {
  5801. value = +value; // convert to a number
  5802. if (value === 0 || isNaN(value))
  5803. return value;
  5804. return value > 0 ? 1 : -1;
  5805. };
  5806. /**
  5807. * Returns the value itself if it's between min and max.
  5808. * Returns min if the value is lower than min.
  5809. * Returns max if the value is greater than max.
  5810. */
  5811. Scalar.Clamp = function (value, min, max) {
  5812. if (min === void 0) { min = 0; }
  5813. if (max === void 0) { max = 1; }
  5814. return Math.min(max, Math.max(min, value));
  5815. };
  5816. /**
  5817. * Returns the log2 of value.
  5818. */
  5819. Scalar.Log2 = function (value) {
  5820. return Math.log(value) * Math.LOG2E;
  5821. };
  5822. /**
  5823. * Loops the value, so that it is never larger than length and never smaller than 0.
  5824. *
  5825. * This is similar to the modulo operator but it works with floating point numbers.
  5826. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  5827. * With t = 5 and length = 2.5, the result would be 0.0.
  5828. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  5829. */
  5830. Scalar.Repeat = function (value, length) {
  5831. return value - Math.floor(value / length) * length;
  5832. };
  5833. /**
  5834. * Normalize the value between 0.0 and 1.0 using min and max values
  5835. */
  5836. Scalar.Normalize = function (value, min, max) {
  5837. return (value - min) / (max - min);
  5838. };
  5839. /**
  5840. * Denormalize the value from 0.0 and 1.0 using min and max values
  5841. */
  5842. Scalar.Denormalize = function (normalized, min, max) {
  5843. return (normalized * (max - min) + min);
  5844. };
  5845. /**
  5846. * Calculates the shortest difference between two given angles given in degrees.
  5847. */
  5848. Scalar.DeltaAngle = function (current, target) {
  5849. var num = Scalar.Repeat(target - current, 360.0);
  5850. if (num > 180.0) {
  5851. num -= 360.0;
  5852. }
  5853. return num;
  5854. };
  5855. /**
  5856. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5857. *
  5858. * The returned value will move back and forth between 0 and length
  5859. */
  5860. Scalar.PingPong = function (tx, length) {
  5861. var t = Scalar.Repeat(tx, length * 2.0);
  5862. return length - Math.abs(t - length);
  5863. };
  5864. /**
  5865. * Interpolates between min and max with smoothing at the limits.
  5866. *
  5867. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5868. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5869. */
  5870. Scalar.SmoothStep = function (from, to, tx) {
  5871. var t = Scalar.Clamp(tx);
  5872. t = -2.0 * t * t * t + 3.0 * t * t;
  5873. return to * t + from * (1.0 - t);
  5874. };
  5875. /**
  5876. * Moves a value current towards target.
  5877. *
  5878. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5879. * Negative values of maxDelta pushes the value away from target.
  5880. */
  5881. Scalar.MoveTowards = function (current, target, maxDelta) {
  5882. var result = 0;
  5883. if (Math.abs(target - current) <= maxDelta) {
  5884. result = target;
  5885. }
  5886. else {
  5887. result = current + Scalar.Sign(target - current) * maxDelta;
  5888. }
  5889. return result;
  5890. };
  5891. /**
  5892. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5893. *
  5894. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5895. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5896. */
  5897. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5898. var num = Scalar.DeltaAngle(current, target);
  5899. var result = 0;
  5900. if (-maxDelta < num && num < maxDelta) {
  5901. result = target;
  5902. }
  5903. else {
  5904. target = current + num;
  5905. result = Scalar.MoveTowards(current, target, maxDelta);
  5906. }
  5907. return result;
  5908. };
  5909. /**
  5910. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5911. */
  5912. Scalar.Lerp = function (start, end, amount) {
  5913. return start + ((end - start) * amount);
  5914. };
  5915. /**
  5916. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5917. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5918. */
  5919. Scalar.LerpAngle = function (start, end, amount) {
  5920. var num = Scalar.Repeat(end - start, 360.0);
  5921. if (num > 180.0) {
  5922. num -= 360.0;
  5923. }
  5924. return start + num * Scalar.Clamp(amount);
  5925. };
  5926. /**
  5927. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5928. */
  5929. Scalar.InverseLerp = function (a, b, value) {
  5930. var result = 0;
  5931. if (a != b) {
  5932. result = Scalar.Clamp((value - a) / (b - a));
  5933. }
  5934. else {
  5935. result = 0.0;
  5936. }
  5937. return result;
  5938. };
  5939. /**
  5940. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5941. */
  5942. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5943. var squared = amount * amount;
  5944. var cubed = amount * squared;
  5945. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5946. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5947. var part3 = (cubed - (2.0 * squared)) + amount;
  5948. var part4 = cubed - squared;
  5949. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5950. };
  5951. /**
  5952. * Returns a random float number between and min and max values
  5953. */
  5954. Scalar.RandomRange = function (min, max) {
  5955. if (min === max)
  5956. return min;
  5957. return ((Math.random() * (max - min)) + min);
  5958. };
  5959. /**
  5960. * This function returns percentage of a number in a given range.
  5961. *
  5962. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5963. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5964. */
  5965. Scalar.RangeToPercent = function (number, min, max) {
  5966. return ((number - min) / (max - min));
  5967. };
  5968. /**
  5969. * This function returns number that corresponds to the percentage in a given range.
  5970. *
  5971. * PercentToRange(0.34,0,100) will return 34.
  5972. */
  5973. Scalar.PercentToRange = function (percent, min, max) {
  5974. return ((max - min) * percent + min);
  5975. };
  5976. /**
  5977. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  5978. * @param angle The angle to normalize in radian.
  5979. * @return The converted angle.
  5980. */
  5981. Scalar.NormalizeRadians = function (angle) {
  5982. // More precise but slower version kept for reference.
  5983. // angle = angle % Tools.TwoPi;
  5984. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  5985. //if (angle > Math.PI) {
  5986. // angle -= Tools.TwoPi;
  5987. //}
  5988. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  5989. return angle;
  5990. };
  5991. /**
  5992. * Two pi constants convenient for computation.
  5993. */
  5994. Scalar.TwoPi = Math.PI * 2;
  5995. return Scalar;
  5996. }());
  5997. BABYLON.Scalar = Scalar;
  5998. })(BABYLON || (BABYLON = {}));
  5999. //# sourceMappingURL=babylon.math.scalar.js.map
  6000. //# sourceMappingURL=babylon.mixins.js.map
  6001. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6002. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6003. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6004. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6005. //# sourceMappingURL=babylon.webgl2.js.map
  6006. var BABYLON;
  6007. (function (BABYLON) {
  6008. var __decoratorInitialStore = {};
  6009. var __mergedStore = {};
  6010. var _copySource = function (creationFunction, source, instanciate) {
  6011. var destination = creationFunction();
  6012. // Tags
  6013. if (BABYLON.Tags) {
  6014. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6015. }
  6016. var classStore = getMergedStore(destination);
  6017. // Properties
  6018. for (var property in classStore) {
  6019. var propertyDescriptor = classStore[property];
  6020. var sourceProperty = source[property];
  6021. var propertyType = propertyDescriptor.type;
  6022. if (sourceProperty !== undefined && sourceProperty !== null) {
  6023. switch (propertyType) {
  6024. case 0: // Value
  6025. case 6:// Mesh reference
  6026. destination[property] = sourceProperty;
  6027. break;
  6028. case 1:// Texture
  6029. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6030. break;
  6031. case 2: // Color3
  6032. case 3: // FresnelParameters
  6033. case 4: // Vector2
  6034. case 5: // Vector3
  6035. case 7: // Color Curves
  6036. case 10:// Quaternion
  6037. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6038. break;
  6039. }
  6040. }
  6041. }
  6042. return destination;
  6043. };
  6044. function getDirectStore(target) {
  6045. var classKey = target.getClassName();
  6046. if (!__decoratorInitialStore[classKey]) {
  6047. __decoratorInitialStore[classKey] = {};
  6048. }
  6049. return __decoratorInitialStore[classKey];
  6050. }
  6051. /**
  6052. * Return the list of properties flagged as serializable
  6053. * @param target: host object
  6054. */
  6055. function getMergedStore(target) {
  6056. var classKey = target.getClassName();
  6057. if (__mergedStore[classKey]) {
  6058. return __mergedStore[classKey];
  6059. }
  6060. __mergedStore[classKey] = {};
  6061. var store = __mergedStore[classKey];
  6062. var currentTarget = target;
  6063. var currentKey = classKey;
  6064. while (currentKey) {
  6065. var initialStore = __decoratorInitialStore[currentKey];
  6066. for (var property in initialStore) {
  6067. store[property] = initialStore[property];
  6068. }
  6069. var parent_1 = void 0;
  6070. var done = false;
  6071. do {
  6072. parent_1 = Object.getPrototypeOf(currentTarget);
  6073. if (!parent_1.getClassName) {
  6074. done = true;
  6075. break;
  6076. }
  6077. if (parent_1.getClassName() !== currentKey) {
  6078. break;
  6079. }
  6080. currentTarget = parent_1;
  6081. } while (parent_1);
  6082. if (done) {
  6083. break;
  6084. }
  6085. currentKey = parent_1.getClassName();
  6086. currentTarget = parent_1;
  6087. }
  6088. return store;
  6089. }
  6090. function generateSerializableMember(type, sourceName) {
  6091. return function (target, propertyKey) {
  6092. var classStore = getDirectStore(target);
  6093. if (!classStore[propertyKey]) {
  6094. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6095. }
  6096. };
  6097. }
  6098. function generateExpandMember(setCallback, targetKey) {
  6099. if (targetKey === void 0) { targetKey = null; }
  6100. return function (target, propertyKey) {
  6101. var key = targetKey || ("_" + propertyKey);
  6102. Object.defineProperty(target, propertyKey, {
  6103. get: function () {
  6104. return this[key];
  6105. },
  6106. set: function (value) {
  6107. if (this[key] === value) {
  6108. return;
  6109. }
  6110. this[key] = value;
  6111. target[setCallback].apply(this);
  6112. },
  6113. enumerable: true,
  6114. configurable: true
  6115. });
  6116. };
  6117. }
  6118. function expandToProperty(callback, targetKey) {
  6119. if (targetKey === void 0) { targetKey = null; }
  6120. return generateExpandMember(callback, targetKey);
  6121. }
  6122. BABYLON.expandToProperty = expandToProperty;
  6123. function serialize(sourceName) {
  6124. return generateSerializableMember(0, sourceName); // value member
  6125. }
  6126. BABYLON.serialize = serialize;
  6127. function serializeAsTexture(sourceName) {
  6128. return generateSerializableMember(1, sourceName); // texture member
  6129. }
  6130. BABYLON.serializeAsTexture = serializeAsTexture;
  6131. function serializeAsColor3(sourceName) {
  6132. return generateSerializableMember(2, sourceName); // color3 member
  6133. }
  6134. BABYLON.serializeAsColor3 = serializeAsColor3;
  6135. function serializeAsFresnelParameters(sourceName) {
  6136. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6137. }
  6138. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6139. function serializeAsVector2(sourceName) {
  6140. return generateSerializableMember(4, sourceName); // vector2 member
  6141. }
  6142. BABYLON.serializeAsVector2 = serializeAsVector2;
  6143. function serializeAsVector3(sourceName) {
  6144. return generateSerializableMember(5, sourceName); // vector3 member
  6145. }
  6146. BABYLON.serializeAsVector3 = serializeAsVector3;
  6147. function serializeAsMeshReference(sourceName) {
  6148. return generateSerializableMember(6, sourceName); // mesh reference member
  6149. }
  6150. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6151. function serializeAsColorCurves(sourceName) {
  6152. return generateSerializableMember(7, sourceName); // color curves
  6153. }
  6154. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6155. function serializeAsColor4(sourceName) {
  6156. return generateSerializableMember(8, sourceName); // color 4
  6157. }
  6158. BABYLON.serializeAsColor4 = serializeAsColor4;
  6159. function serializeAsImageProcessingConfiguration(sourceName) {
  6160. return generateSerializableMember(9, sourceName); // image processing
  6161. }
  6162. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6163. function serializeAsQuaternion(sourceName) {
  6164. return generateSerializableMember(10, sourceName); // quaternion member
  6165. }
  6166. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6167. var SerializationHelper = /** @class */ (function () {
  6168. function SerializationHelper() {
  6169. }
  6170. SerializationHelper.Serialize = function (entity, serializationObject) {
  6171. if (!serializationObject) {
  6172. serializationObject = {};
  6173. }
  6174. // Tags
  6175. if (BABYLON.Tags) {
  6176. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6177. }
  6178. var serializedProperties = getMergedStore(entity);
  6179. // Properties
  6180. for (var property in serializedProperties) {
  6181. var propertyDescriptor = serializedProperties[property];
  6182. var targetPropertyName = propertyDescriptor.sourceName || property;
  6183. var propertyType = propertyDescriptor.type;
  6184. var sourceProperty = entity[property];
  6185. if (sourceProperty !== undefined && sourceProperty !== null) {
  6186. switch (propertyType) {
  6187. case 0:// Value
  6188. serializationObject[targetPropertyName] = sourceProperty;
  6189. break;
  6190. case 1:// Texture
  6191. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6192. break;
  6193. case 2:// Color3
  6194. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6195. break;
  6196. case 3:// FresnelParameters
  6197. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6198. break;
  6199. case 4:// Vector2
  6200. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6201. break;
  6202. case 5:// Vector3
  6203. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6204. break;
  6205. case 6:// Mesh reference
  6206. serializationObject[targetPropertyName] = sourceProperty.id;
  6207. break;
  6208. case 7:// Color Curves
  6209. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6210. break;
  6211. case 8:// Color 4
  6212. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6213. break;
  6214. case 9:// Image Processing
  6215. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6216. break;
  6217. }
  6218. }
  6219. }
  6220. return serializationObject;
  6221. };
  6222. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6223. if (rootUrl === void 0) { rootUrl = null; }
  6224. var destination = creationFunction();
  6225. if (!rootUrl) {
  6226. rootUrl = "";
  6227. }
  6228. // Tags
  6229. if (BABYLON.Tags) {
  6230. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6231. }
  6232. var classStore = getMergedStore(destination);
  6233. // Properties
  6234. for (var property in classStore) {
  6235. var propertyDescriptor = classStore[property];
  6236. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6237. var propertyType = propertyDescriptor.type;
  6238. if (sourceProperty !== undefined && sourceProperty !== null) {
  6239. var dest = destination;
  6240. switch (propertyType) {
  6241. case 0:// Value
  6242. dest[property] = sourceProperty;
  6243. break;
  6244. case 1:// Texture
  6245. if (scene) {
  6246. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6247. }
  6248. break;
  6249. case 2:// Color3
  6250. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6251. break;
  6252. case 3:// FresnelParameters
  6253. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6254. break;
  6255. case 4:// Vector2
  6256. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6257. break;
  6258. case 5:// Vector3
  6259. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6260. break;
  6261. case 6:// Mesh reference
  6262. if (scene) {
  6263. dest[property] = scene.getLastMeshByID(sourceProperty);
  6264. }
  6265. break;
  6266. case 7:// Color Curves
  6267. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6268. break;
  6269. case 8:// Color 4
  6270. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6271. break;
  6272. case 9:// Image Processing
  6273. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6274. break;
  6275. }
  6276. }
  6277. }
  6278. return destination;
  6279. };
  6280. SerializationHelper.Clone = function (creationFunction, source) {
  6281. return _copySource(creationFunction, source, false);
  6282. };
  6283. SerializationHelper.Instanciate = function (creationFunction, source) {
  6284. return _copySource(creationFunction, source, true);
  6285. };
  6286. return SerializationHelper;
  6287. }());
  6288. BABYLON.SerializationHelper = SerializationHelper;
  6289. })(BABYLON || (BABYLON = {}));
  6290. //# sourceMappingURL=babylon.decorators.js.map
  6291. var BABYLON;
  6292. (function (BABYLON) {
  6293. /**
  6294. * A class serves as a medium between the observable and its observers
  6295. */
  6296. var EventState = /** @class */ (function () {
  6297. /**
  6298. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6299. */
  6300. function EventState(mask, skipNextObservers, target, currentTarget) {
  6301. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6302. this.initalize(mask, skipNextObservers, target, currentTarget);
  6303. }
  6304. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6305. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6306. this.mask = mask;
  6307. this.skipNextObservers = skipNextObservers;
  6308. this.target = target;
  6309. this.currentTarget = currentTarget;
  6310. return this;
  6311. };
  6312. return EventState;
  6313. }());
  6314. BABYLON.EventState = EventState;
  6315. /**
  6316. * Represent an Observer registered to a given Observable object.
  6317. */
  6318. var Observer = /** @class */ (function () {
  6319. function Observer(callback, mask, scope) {
  6320. if (scope === void 0) { scope = null; }
  6321. this.callback = callback;
  6322. this.mask = mask;
  6323. this.scope = scope;
  6324. }
  6325. return Observer;
  6326. }());
  6327. BABYLON.Observer = Observer;
  6328. /**
  6329. * Represent a list of observers registered to multiple Observables object.
  6330. */
  6331. var MultiObserver = /** @class */ (function () {
  6332. function MultiObserver() {
  6333. }
  6334. MultiObserver.prototype.dispose = function () {
  6335. if (this._observers && this._observables) {
  6336. for (var index = 0; index < this._observers.length; index++) {
  6337. this._observables[index].remove(this._observers[index]);
  6338. }
  6339. }
  6340. this._observers = null;
  6341. this._observables = null;
  6342. };
  6343. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6344. if (mask === void 0) { mask = -1; }
  6345. if (scope === void 0) { scope = null; }
  6346. var result = new MultiObserver();
  6347. result._observers = new Array();
  6348. result._observables = observables;
  6349. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6350. var observable = observables_1[_i];
  6351. var observer = observable.add(callback, mask, false, scope);
  6352. if (observer) {
  6353. result._observers.push(observer);
  6354. }
  6355. }
  6356. return result;
  6357. };
  6358. return MultiObserver;
  6359. }());
  6360. BABYLON.MultiObserver = MultiObserver;
  6361. /**
  6362. * The Observable class is a simple implementation of the Observable pattern.
  6363. * 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.
  6364. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6365. * 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).
  6366. * 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.
  6367. */
  6368. var Observable = /** @class */ (function () {
  6369. function Observable(onObserverAdded) {
  6370. this._observers = new Array();
  6371. this._eventState = new EventState(0);
  6372. if (onObserverAdded) {
  6373. this._onObserverAdded = onObserverAdded;
  6374. }
  6375. }
  6376. /**
  6377. * Create a new Observer with the specified callback
  6378. * @param callback the callback that will be executed for that Observer
  6379. * @param mask the mask used to filter observers
  6380. * @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.
  6381. * @param scope optional scope for the callback to be called from
  6382. */
  6383. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6384. if (mask === void 0) { mask = -1; }
  6385. if (insertFirst === void 0) { insertFirst = false; }
  6386. if (scope === void 0) { scope = null; }
  6387. if (!callback) {
  6388. return null;
  6389. }
  6390. var observer = new Observer(callback, mask, scope);
  6391. if (insertFirst) {
  6392. this._observers.unshift(observer);
  6393. }
  6394. else {
  6395. this._observers.push(observer);
  6396. }
  6397. if (this._onObserverAdded) {
  6398. this._onObserverAdded(observer);
  6399. }
  6400. return observer;
  6401. };
  6402. /**
  6403. * Remove an Observer from the Observable object
  6404. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6405. */
  6406. Observable.prototype.remove = function (observer) {
  6407. if (!observer) {
  6408. return false;
  6409. }
  6410. var index = this._observers.indexOf(observer);
  6411. if (index !== -1) {
  6412. this._observers.splice(index, 1);
  6413. return true;
  6414. }
  6415. return false;
  6416. };
  6417. /**
  6418. * Remove a callback from the Observable object
  6419. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6420. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6421. */
  6422. Observable.prototype.removeCallback = function (callback, scope) {
  6423. for (var index = 0; index < this._observers.length; index++) {
  6424. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6425. this._observers.splice(index, 1);
  6426. return true;
  6427. }
  6428. }
  6429. return false;
  6430. };
  6431. /**
  6432. * Notify all Observers by calling their respective callback with the given data
  6433. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6434. * @param eventData
  6435. * @param mask
  6436. */
  6437. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6438. if (mask === void 0) { mask = -1; }
  6439. if (!this._observers.length) {
  6440. return true;
  6441. }
  6442. var state = this._eventState;
  6443. state.mask = mask;
  6444. state.target = target;
  6445. state.currentTarget = currentTarget;
  6446. state.skipNextObservers = false;
  6447. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6448. var obs = _a[_i];
  6449. if (obs.mask & mask) {
  6450. if (obs.scope) {
  6451. obs.callback.apply(obs.scope, [eventData, state]);
  6452. }
  6453. else {
  6454. obs.callback(eventData, state);
  6455. }
  6456. }
  6457. if (state.skipNextObservers) {
  6458. return false;
  6459. }
  6460. }
  6461. return true;
  6462. };
  6463. /**
  6464. * Notify a specific observer
  6465. * @param eventData
  6466. * @param mask
  6467. */
  6468. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6469. if (mask === void 0) { mask = -1; }
  6470. var state = this._eventState;
  6471. state.mask = mask;
  6472. state.skipNextObservers = false;
  6473. observer.callback(eventData, state);
  6474. };
  6475. /**
  6476. * return true is the Observable has at least one Observer registered
  6477. */
  6478. Observable.prototype.hasObservers = function () {
  6479. return this._observers.length > 0;
  6480. };
  6481. /**
  6482. * Clear the list of observers
  6483. */
  6484. Observable.prototype.clear = function () {
  6485. this._observers = new Array();
  6486. this._onObserverAdded = null;
  6487. };
  6488. /**
  6489. * Clone the current observable
  6490. */
  6491. Observable.prototype.clone = function () {
  6492. var result = new Observable();
  6493. result._observers = this._observers.slice(0);
  6494. return result;
  6495. };
  6496. /**
  6497. * Does this observable handles observer registered with a given mask
  6498. * @param {number} trigger - the mask to be tested
  6499. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6500. **/
  6501. Observable.prototype.hasSpecificMask = function (mask) {
  6502. if (mask === void 0) { mask = -1; }
  6503. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6504. var obs = _a[_i];
  6505. if (obs.mask & mask || obs.mask === mask) {
  6506. return true;
  6507. }
  6508. }
  6509. return false;
  6510. };
  6511. return Observable;
  6512. }());
  6513. BABYLON.Observable = Observable;
  6514. })(BABYLON || (BABYLON = {}));
  6515. //# sourceMappingURL=babylon.observable.js.map
  6516. var BABYLON;
  6517. (function (BABYLON) {
  6518. var SmartArray = /** @class */ (function () {
  6519. function SmartArray(capacity) {
  6520. this.length = 0;
  6521. this.data = new Array(capacity);
  6522. this._id = SmartArray._GlobalId++;
  6523. }
  6524. SmartArray.prototype.push = function (value) {
  6525. this.data[this.length++] = value;
  6526. if (this.length > this.data.length) {
  6527. this.data.length *= 2;
  6528. }
  6529. };
  6530. SmartArray.prototype.forEach = function (func) {
  6531. for (var index = 0; index < this.length; index++) {
  6532. func(this.data[index]);
  6533. }
  6534. };
  6535. SmartArray.prototype.sort = function (compareFn) {
  6536. this.data.sort(compareFn);
  6537. };
  6538. SmartArray.prototype.reset = function () {
  6539. this.length = 0;
  6540. };
  6541. SmartArray.prototype.dispose = function () {
  6542. this.reset();
  6543. if (this.data) {
  6544. this.data.length = 0;
  6545. this.data = [];
  6546. }
  6547. };
  6548. SmartArray.prototype.concat = function (array) {
  6549. if (array.length === 0) {
  6550. return;
  6551. }
  6552. if (this.length + array.length > this.data.length) {
  6553. this.data.length = (this.length + array.length) * 2;
  6554. }
  6555. for (var index = 0; index < array.length; index++) {
  6556. this.data[this.length++] = (array.data || array)[index];
  6557. }
  6558. };
  6559. SmartArray.prototype.indexOf = function (value) {
  6560. var position = this.data.indexOf(value);
  6561. if (position >= this.length) {
  6562. return -1;
  6563. }
  6564. return position;
  6565. };
  6566. SmartArray.prototype.contains = function (value) {
  6567. return this.data.indexOf(value) !== -1;
  6568. };
  6569. // Statics
  6570. SmartArray._GlobalId = 0;
  6571. return SmartArray;
  6572. }());
  6573. BABYLON.SmartArray = SmartArray;
  6574. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6575. __extends(SmartArrayNoDuplicate, _super);
  6576. function SmartArrayNoDuplicate() {
  6577. var _this = _super !== null && _super.apply(this, arguments) || this;
  6578. _this._duplicateId = 0;
  6579. return _this;
  6580. }
  6581. SmartArrayNoDuplicate.prototype.push = function (value) {
  6582. _super.prototype.push.call(this, value);
  6583. if (!value.__smartArrayFlags) {
  6584. value.__smartArrayFlags = {};
  6585. }
  6586. value.__smartArrayFlags[this._id] = this._duplicateId;
  6587. };
  6588. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6589. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6590. return false;
  6591. }
  6592. this.push(value);
  6593. return true;
  6594. };
  6595. SmartArrayNoDuplicate.prototype.reset = function () {
  6596. _super.prototype.reset.call(this);
  6597. this._duplicateId++;
  6598. };
  6599. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6600. if (array.length === 0) {
  6601. return;
  6602. }
  6603. if (this.length + array.length > this.data.length) {
  6604. this.data.length = (this.length + array.length) * 2;
  6605. }
  6606. for (var index = 0; index < array.length; index++) {
  6607. var item = (array.data || array)[index];
  6608. this.pushNoDuplicate(item);
  6609. }
  6610. };
  6611. return SmartArrayNoDuplicate;
  6612. }(SmartArray));
  6613. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6614. })(BABYLON || (BABYLON = {}));
  6615. //# sourceMappingURL=babylon.smartArray.js.map
  6616. var BABYLON;
  6617. (function (BABYLON) {
  6618. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6619. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6620. var LoadFileError = /** @class */ (function (_super) {
  6621. __extends(LoadFileError, _super);
  6622. function LoadFileError(message, request) {
  6623. var _this = _super.call(this, message) || this;
  6624. _this.request = request;
  6625. _this.name = "LoadFileError";
  6626. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6627. return _this;
  6628. }
  6629. // Polyfill for Object.setPrototypeOf if necessary.
  6630. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6631. return LoadFileError;
  6632. }(Error));
  6633. BABYLON.LoadFileError = LoadFileError;
  6634. var RetryStrategy = /** @class */ (function () {
  6635. function RetryStrategy() {
  6636. }
  6637. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6638. if (maxRetries === void 0) { maxRetries = 3; }
  6639. if (baseInterval === void 0) { baseInterval = 500; }
  6640. return function (url, request, retryIndex) {
  6641. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6642. return -1;
  6643. }
  6644. return Math.pow(2, retryIndex) * baseInterval;
  6645. };
  6646. };
  6647. return RetryStrategy;
  6648. }());
  6649. BABYLON.RetryStrategy = RetryStrategy;
  6650. // Screenshots
  6651. var screenshotCanvas;
  6652. var cloneValue = function (source, destinationObject) {
  6653. if (!source)
  6654. return null;
  6655. if (source instanceof BABYLON.Mesh) {
  6656. return null;
  6657. }
  6658. if (source instanceof BABYLON.SubMesh) {
  6659. return source.clone(destinationObject);
  6660. }
  6661. else if (source.clone) {
  6662. return source.clone();
  6663. }
  6664. return null;
  6665. };
  6666. var Tools = /** @class */ (function () {
  6667. function Tools() {
  6668. }
  6669. /**
  6670. * Interpolates between a and b via alpha
  6671. * @param a The lower value (returned when alpha = 0)
  6672. * @param b The upper value (returned when alpha = 1)
  6673. * @param alpha The interpolation-factor
  6674. * @return The mixed value
  6675. */
  6676. Tools.Mix = function (a, b, alpha) {
  6677. return a * (1 - alpha) + b * alpha;
  6678. };
  6679. Tools.Instantiate = function (className) {
  6680. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6681. return Tools.RegisteredExternalClasses[className];
  6682. }
  6683. var arr = className.split(".");
  6684. var fn = (window || this);
  6685. for (var i = 0, len = arr.length; i < len; i++) {
  6686. fn = fn[arr[i]];
  6687. }
  6688. if (typeof fn !== "function") {
  6689. return null;
  6690. }
  6691. return fn;
  6692. };
  6693. Tools.SetImmediate = function (action) {
  6694. if (window.setImmediate) {
  6695. window.setImmediate(action);
  6696. }
  6697. else {
  6698. setTimeout(action, 1);
  6699. }
  6700. };
  6701. Tools.IsExponentOfTwo = function (value) {
  6702. var count = 1;
  6703. do {
  6704. count *= 2;
  6705. } while (count < value);
  6706. return count === value;
  6707. };
  6708. /**
  6709. * Find the next highest power of two.
  6710. * @param x Number to start search from.
  6711. * @return Next highest power of two.
  6712. */
  6713. Tools.CeilingPOT = function (x) {
  6714. x--;
  6715. x |= x >> 1;
  6716. x |= x >> 2;
  6717. x |= x >> 4;
  6718. x |= x >> 8;
  6719. x |= x >> 16;
  6720. x++;
  6721. return x;
  6722. };
  6723. /**
  6724. * Find the next lowest power of two.
  6725. * @param x Number to start search from.
  6726. * @return Next lowest power of two.
  6727. */
  6728. Tools.FloorPOT = function (x) {
  6729. x = x | (x >> 1);
  6730. x = x | (x >> 2);
  6731. x = x | (x >> 4);
  6732. x = x | (x >> 8);
  6733. x = x | (x >> 16);
  6734. return x - (x >> 1);
  6735. };
  6736. /**
  6737. * Find the nearest power of two.
  6738. * @param x Number to start search from.
  6739. * @return Next nearest power of two.
  6740. */
  6741. Tools.NearestPOT = function (x) {
  6742. var c = Tools.CeilingPOT(x);
  6743. var f = Tools.FloorPOT(x);
  6744. return (c - x) > (x - f) ? f : c;
  6745. };
  6746. Tools.GetExponentOfTwo = function (value, max, mode) {
  6747. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  6748. var pot;
  6749. switch (mode) {
  6750. case BABYLON.Engine.SCALEMODE_FLOOR:
  6751. pot = Tools.FloorPOT(value);
  6752. break;
  6753. case BABYLON.Engine.SCALEMODE_NEAREST:
  6754. pot = Tools.NearestPOT(value);
  6755. break;
  6756. case BABYLON.Engine.SCALEMODE_CEILING:
  6757. default:
  6758. pot = Tools.CeilingPOT(value);
  6759. break;
  6760. }
  6761. return Math.min(pot, max);
  6762. };
  6763. Tools.GetFilename = function (path) {
  6764. var index = path.lastIndexOf("/");
  6765. if (index < 0)
  6766. return path;
  6767. return path.substring(index + 1);
  6768. };
  6769. Tools.GetFolderPath = function (uri) {
  6770. var index = uri.lastIndexOf("/");
  6771. if (index < 0)
  6772. return "";
  6773. return uri.substring(0, index + 1);
  6774. };
  6775. Tools.GetDOMTextContent = function (element) {
  6776. var result = "";
  6777. var child = element.firstChild;
  6778. while (child) {
  6779. if (child.nodeType === 3) {
  6780. result += child.textContent;
  6781. }
  6782. child = child.nextSibling;
  6783. }
  6784. return result;
  6785. };
  6786. Tools.ToDegrees = function (angle) {
  6787. return angle * 180 / Math.PI;
  6788. };
  6789. Tools.ToRadians = function (angle) {
  6790. return angle * Math.PI / 180;
  6791. };
  6792. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6793. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6794. var output = "";
  6795. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6796. var i = 0;
  6797. var bytes = new Uint8Array(buffer);
  6798. while (i < bytes.length) {
  6799. chr1 = bytes[i++];
  6800. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6801. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6802. enc1 = chr1 >> 2;
  6803. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6804. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6805. enc4 = chr3 & 63;
  6806. if (isNaN(chr2)) {
  6807. enc3 = enc4 = 64;
  6808. }
  6809. else if (isNaN(chr3)) {
  6810. enc4 = 64;
  6811. }
  6812. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6813. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6814. }
  6815. return "data:image/png;base64," + output;
  6816. };
  6817. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6818. if (bias === void 0) { bias = null; }
  6819. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6820. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6821. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6822. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6823. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6824. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6825. }
  6826. if (bias) {
  6827. minimum.x -= minimum.x * bias.x + bias.y;
  6828. minimum.y -= minimum.y * bias.x + bias.y;
  6829. minimum.z -= minimum.z * bias.x + bias.y;
  6830. maximum.x += maximum.x * bias.x + bias.y;
  6831. maximum.y += maximum.y * bias.x + bias.y;
  6832. maximum.z += maximum.z * bias.x + bias.y;
  6833. }
  6834. return {
  6835. minimum: minimum,
  6836. maximum: maximum
  6837. };
  6838. };
  6839. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6840. if (bias === void 0) { bias = null; }
  6841. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6842. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6843. if (!stride) {
  6844. stride = 3;
  6845. }
  6846. for (var index = start; index < start + count; index++) {
  6847. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6848. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6849. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6850. }
  6851. if (bias) {
  6852. minimum.x -= minimum.x * bias.x + bias.y;
  6853. minimum.y -= minimum.y * bias.x + bias.y;
  6854. minimum.z -= minimum.z * bias.x + bias.y;
  6855. maximum.x += maximum.x * bias.x + bias.y;
  6856. maximum.y += maximum.y * bias.x + bias.y;
  6857. maximum.z += maximum.z * bias.x + bias.y;
  6858. }
  6859. return {
  6860. minimum: minimum,
  6861. maximum: maximum
  6862. };
  6863. };
  6864. Tools.Vector2ArrayFeeder = function (array) {
  6865. return function (index) {
  6866. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6867. var length = isFloatArray ? array.length / 2 : array.length;
  6868. if (index >= length) {
  6869. return null;
  6870. }
  6871. if (isFloatArray) {
  6872. var fa = array;
  6873. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6874. }
  6875. var a = array;
  6876. return a[index];
  6877. };
  6878. };
  6879. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6880. if (bias === void 0) { bias = null; }
  6881. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6882. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6883. var i = 0;
  6884. var cur = feeder(i++);
  6885. while (cur) {
  6886. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6887. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6888. cur = feeder(i++);
  6889. }
  6890. if (bias) {
  6891. minimum.x -= minimum.x * bias.x + bias.y;
  6892. minimum.y -= minimum.y * bias.x + bias.y;
  6893. maximum.x += maximum.x * bias.x + bias.y;
  6894. maximum.y += maximum.y * bias.x + bias.y;
  6895. }
  6896. return {
  6897. minimum: minimum,
  6898. maximum: maximum
  6899. };
  6900. };
  6901. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6902. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6903. return null;
  6904. return Array.isArray(obj) ? obj : [obj];
  6905. };
  6906. // Misc.
  6907. Tools.GetPointerPrefix = function () {
  6908. var eventPrefix = "pointer";
  6909. // Check if pointer events are supported
  6910. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6911. eventPrefix = "mouse";
  6912. }
  6913. return eventPrefix;
  6914. };
  6915. /**
  6916. * @param func - the function to be called
  6917. * @param requester - the object that will request the next frame. Falls back to window.
  6918. */
  6919. Tools.QueueNewFrame = function (func, requester) {
  6920. if (!Tools.IsWindowObjectExist()) {
  6921. return setTimeout(func, 16);
  6922. }
  6923. if (!requester) {
  6924. requester = window;
  6925. }
  6926. if (requester.requestAnimationFrame) {
  6927. return requester.requestAnimationFrame(func);
  6928. }
  6929. else if (requester.msRequestAnimationFrame) {
  6930. return requester.msRequestAnimationFrame(func);
  6931. }
  6932. else if (requester.webkitRequestAnimationFrame) {
  6933. return requester.webkitRequestAnimationFrame(func);
  6934. }
  6935. else if (requester.mozRequestAnimationFrame) {
  6936. return requester.mozRequestAnimationFrame(func);
  6937. }
  6938. else if (requester.oRequestAnimationFrame) {
  6939. return requester.oRequestAnimationFrame(func);
  6940. }
  6941. else {
  6942. return window.setTimeout(func, 16);
  6943. }
  6944. };
  6945. Tools.RequestFullscreen = function (element) {
  6946. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6947. if (!requestFunction)
  6948. return;
  6949. requestFunction.call(element);
  6950. };
  6951. Tools.ExitFullscreen = function () {
  6952. if (document.exitFullscreen) {
  6953. document.exitFullscreen();
  6954. }
  6955. else if (document.mozCancelFullScreen) {
  6956. document.mozCancelFullScreen();
  6957. }
  6958. else if (document.webkitCancelFullScreen) {
  6959. document.webkitCancelFullScreen();
  6960. }
  6961. else if (document.msCancelFullScreen) {
  6962. document.msCancelFullScreen();
  6963. }
  6964. };
  6965. Tools.SetCorsBehavior = function (url, element) {
  6966. if (url && url.indexOf("data:") === 0) {
  6967. return;
  6968. }
  6969. if (Tools.CorsBehavior) {
  6970. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  6971. element.crossOrigin = Tools.CorsBehavior;
  6972. }
  6973. else {
  6974. var result = Tools.CorsBehavior(url);
  6975. if (result) {
  6976. element.crossOrigin = result;
  6977. }
  6978. }
  6979. }
  6980. };
  6981. // External files
  6982. Tools.CleanUrl = function (url) {
  6983. url = url.replace(/#/mg, "%23");
  6984. return url;
  6985. };
  6986. Tools.LoadImage = function (url, onLoad, onError, database) {
  6987. if (url instanceof ArrayBuffer) {
  6988. url = Tools.EncodeArrayBufferTobase64(url);
  6989. }
  6990. url = Tools.CleanUrl(url);
  6991. url = Tools.PreprocessUrl(url);
  6992. var img = new Image();
  6993. Tools.SetCorsBehavior(url, img);
  6994. img.onload = function () {
  6995. onLoad(img);
  6996. };
  6997. img.onerror = function (err) {
  6998. Tools.Error("Error while trying to load image: " + url);
  6999. if (onError) {
  7000. onError("Error while trying to load image: " + url, err);
  7001. }
  7002. };
  7003. var noIndexedDB = function () {
  7004. img.src = url;
  7005. };
  7006. var loadFromIndexedDB = function () {
  7007. if (database) {
  7008. database.loadImageFromDB(url, img);
  7009. }
  7010. };
  7011. //ANY database to do!
  7012. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7013. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7014. }
  7015. else {
  7016. if (url.indexOf("file:") !== -1) {
  7017. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7018. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7019. try {
  7020. var blobURL;
  7021. try {
  7022. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7023. }
  7024. catch (ex) {
  7025. // Chrome doesn't support oneTimeOnly parameter
  7026. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7027. }
  7028. img.src = blobURL;
  7029. }
  7030. catch (e) {
  7031. img.src = "";
  7032. }
  7033. return img;
  7034. }
  7035. }
  7036. noIndexedDB();
  7037. }
  7038. return img;
  7039. };
  7040. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7041. url = Tools.CleanUrl(url);
  7042. url = Tools.PreprocessUrl(url);
  7043. // If file and file input are set
  7044. if (url.indexOf("file:") !== -1) {
  7045. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7046. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7047. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7048. }
  7049. }
  7050. var loadUrl = Tools.BaseUrl + url;
  7051. var aborted = false;
  7052. var fileRequest = {
  7053. onCompleteObservable: new BABYLON.Observable(),
  7054. abort: function () { return aborted = true; },
  7055. };
  7056. var requestFile = function () {
  7057. var request = new XMLHttpRequest();
  7058. var retryHandle = null;
  7059. fileRequest.abort = function () {
  7060. aborted = true;
  7061. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7062. request.abort();
  7063. }
  7064. if (retryHandle !== null) {
  7065. clearTimeout(retryHandle);
  7066. retryHandle = null;
  7067. }
  7068. };
  7069. var retryLoop = function (retryIndex) {
  7070. request.open('GET', loadUrl, true);
  7071. if (useArrayBuffer) {
  7072. request.responseType = "arraybuffer";
  7073. }
  7074. if (onProgress) {
  7075. request.addEventListener("progress", onProgress);
  7076. }
  7077. var onLoadEnd = function () {
  7078. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7079. };
  7080. request.addEventListener("loadend", onLoadEnd);
  7081. var onReadyStateChange = function () {
  7082. if (aborted) {
  7083. return;
  7084. }
  7085. // In case of undefined state in some browsers.
  7086. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7087. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7088. request.removeEventListener("readystatechange", onReadyStateChange);
  7089. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7090. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7091. return;
  7092. }
  7093. var retryStrategy = Tools.DefaultRetryStrategy;
  7094. if (retryStrategy) {
  7095. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7096. if (waitTime !== -1) {
  7097. // Prevent the request from completing for retry.
  7098. request.removeEventListener("loadend", onLoadEnd);
  7099. request = new XMLHttpRequest();
  7100. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7101. return;
  7102. }
  7103. }
  7104. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7105. if (onError) {
  7106. onError(request, e);
  7107. }
  7108. else {
  7109. throw e;
  7110. }
  7111. }
  7112. };
  7113. request.addEventListener("readystatechange", onReadyStateChange);
  7114. request.send();
  7115. };
  7116. retryLoop(0);
  7117. };
  7118. // Caching all files
  7119. if (database && database.enableSceneOffline) {
  7120. var noIndexedDB_1 = function () {
  7121. if (!aborted) {
  7122. requestFile();
  7123. }
  7124. };
  7125. var loadFromIndexedDB = function () {
  7126. // TODO: database needs to support aborting and should return a IFileRequest
  7127. if (aborted) {
  7128. return;
  7129. }
  7130. if (database) {
  7131. database.loadFileFromDB(url, function (data) {
  7132. if (!aborted) {
  7133. onSuccess(data);
  7134. }
  7135. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7136. }, onProgress ? function (event) {
  7137. if (!aborted) {
  7138. onProgress(event);
  7139. }
  7140. } : undefined, noIndexedDB_1, useArrayBuffer);
  7141. }
  7142. };
  7143. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7144. }
  7145. else {
  7146. requestFile();
  7147. }
  7148. return fileRequest;
  7149. };
  7150. /**
  7151. * Load a script (identified by an url). When the url returns, the
  7152. * content of this file is added into a new script element, attached to the DOM (body element)
  7153. */
  7154. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7155. var head = document.getElementsByTagName('head')[0];
  7156. var script = document.createElement('script');
  7157. script.type = 'text/javascript';
  7158. script.src = scriptUrl;
  7159. script.onload = function () {
  7160. if (onSuccess) {
  7161. onSuccess();
  7162. }
  7163. };
  7164. script.onerror = function (e) {
  7165. if (onError) {
  7166. onError("Unable to load script", e);
  7167. }
  7168. };
  7169. head.appendChild(script);
  7170. };
  7171. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7172. var reader = new FileReader();
  7173. var request = {
  7174. onCompleteObservable: new BABYLON.Observable(),
  7175. abort: function () { return reader.abort(); },
  7176. };
  7177. reader.onloadend = function (e) {
  7178. request.onCompleteObservable.notifyObservers(request);
  7179. };
  7180. reader.onload = function (e) {
  7181. //target doesn't have result from ts 1.3
  7182. callback(e.target['result']);
  7183. };
  7184. reader.onprogress = progressCallback;
  7185. reader.readAsDataURL(fileToLoad);
  7186. return request;
  7187. };
  7188. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7189. var reader = new FileReader();
  7190. var request = {
  7191. onCompleteObservable: new BABYLON.Observable(),
  7192. abort: function () { return reader.abort(); },
  7193. };
  7194. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7195. reader.onerror = function (e) {
  7196. Tools.Log("Error while reading file: " + fileToLoad.name);
  7197. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7198. };
  7199. reader.onload = function (e) {
  7200. //target doesn't have result from ts 1.3
  7201. callback(e.target['result']);
  7202. };
  7203. if (progressCallBack) {
  7204. reader.onprogress = progressCallBack;
  7205. }
  7206. if (!useArrayBuffer) {
  7207. // Asynchronous read
  7208. reader.readAsText(fileToLoad);
  7209. }
  7210. else {
  7211. reader.readAsArrayBuffer(fileToLoad);
  7212. }
  7213. return request;
  7214. };
  7215. //returns a downloadable url to a file content.
  7216. Tools.FileAsURL = function (content) {
  7217. var fileBlob = new Blob([content]);
  7218. var url = window.URL || window.webkitURL;
  7219. var link = url.createObjectURL(fileBlob);
  7220. return link;
  7221. };
  7222. // Misc.
  7223. Tools.Format = function (value, decimals) {
  7224. if (decimals === void 0) { decimals = 2; }
  7225. return value.toFixed(decimals);
  7226. };
  7227. Tools.CheckExtends = function (v, min, max) {
  7228. if (v.x < min.x)
  7229. min.x = v.x;
  7230. if (v.y < min.y)
  7231. min.y = v.y;
  7232. if (v.z < min.z)
  7233. min.z = v.z;
  7234. if (v.x > max.x)
  7235. max.x = v.x;
  7236. if (v.y > max.y)
  7237. max.y = v.y;
  7238. if (v.z > max.z)
  7239. max.z = v.z;
  7240. };
  7241. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7242. for (var prop in source) {
  7243. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7244. continue;
  7245. }
  7246. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7247. continue;
  7248. }
  7249. var sourceValue = source[prop];
  7250. var typeOfSourceValue = typeof sourceValue;
  7251. if (typeOfSourceValue === "function") {
  7252. continue;
  7253. }
  7254. if (typeOfSourceValue === "object") {
  7255. if (sourceValue instanceof Array) {
  7256. destination[prop] = [];
  7257. if (sourceValue.length > 0) {
  7258. if (typeof sourceValue[0] == "object") {
  7259. for (var index = 0; index < sourceValue.length; index++) {
  7260. var clonedValue = cloneValue(sourceValue[index], destination);
  7261. if (destination[prop].indexOf(clonedValue) === -1) {
  7262. destination[prop].push(clonedValue);
  7263. }
  7264. }
  7265. }
  7266. else {
  7267. destination[prop] = sourceValue.slice(0);
  7268. }
  7269. }
  7270. }
  7271. else {
  7272. destination[prop] = cloneValue(sourceValue, destination);
  7273. }
  7274. }
  7275. else {
  7276. destination[prop] = sourceValue;
  7277. }
  7278. }
  7279. };
  7280. Tools.IsEmpty = function (obj) {
  7281. for (var i in obj) {
  7282. if (obj.hasOwnProperty(i)) {
  7283. return false;
  7284. }
  7285. }
  7286. return true;
  7287. };
  7288. Tools.RegisterTopRootEvents = function (events) {
  7289. for (var index = 0; index < events.length; index++) {
  7290. var event = events[index];
  7291. window.addEventListener(event.name, event.handler, false);
  7292. try {
  7293. if (window.parent) {
  7294. window.parent.addEventListener(event.name, event.handler, false);
  7295. }
  7296. }
  7297. catch (e) {
  7298. // Silently fails...
  7299. }
  7300. }
  7301. };
  7302. Tools.UnregisterTopRootEvents = function (events) {
  7303. for (var index = 0; index < events.length; index++) {
  7304. var event = events[index];
  7305. window.removeEventListener(event.name, event.handler);
  7306. try {
  7307. if (window.parent) {
  7308. window.parent.removeEventListener(event.name, event.handler);
  7309. }
  7310. }
  7311. catch (e) {
  7312. // Silently fails...
  7313. }
  7314. }
  7315. };
  7316. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7317. if (mimeType === void 0) { mimeType = "image/png"; }
  7318. // Read the contents of the framebuffer
  7319. var numberOfChannelsByLine = width * 4;
  7320. var halfHeight = height / 2;
  7321. //Reading datas from WebGL
  7322. var data = engine.readPixels(0, 0, width, height);
  7323. //To flip image on Y axis.
  7324. for (var i = 0; i < halfHeight; i++) {
  7325. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7326. var currentCell = j + i * numberOfChannelsByLine;
  7327. var targetLine = height - i - 1;
  7328. var targetCell = j + targetLine * numberOfChannelsByLine;
  7329. var temp = data[currentCell];
  7330. data[currentCell] = data[targetCell];
  7331. data[targetCell] = temp;
  7332. }
  7333. }
  7334. // Create a 2D canvas to store the result
  7335. if (!screenshotCanvas) {
  7336. screenshotCanvas = document.createElement('canvas');
  7337. }
  7338. screenshotCanvas.width = width;
  7339. screenshotCanvas.height = height;
  7340. var context = screenshotCanvas.getContext('2d');
  7341. if (context) {
  7342. // Copy the pixels to a 2D canvas
  7343. var imageData = context.createImageData(width, height);
  7344. var castData = (imageData.data);
  7345. castData.set(data);
  7346. context.putImageData(imageData, 0, 0);
  7347. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7348. }
  7349. };
  7350. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7351. if (mimeType === void 0) { mimeType = "image/png"; }
  7352. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7353. if (successCallback) {
  7354. successCallback(base64Image);
  7355. }
  7356. else {
  7357. // We need HTMLCanvasElement.toBlob for HD screenshots
  7358. if (!screenshotCanvas.toBlob) {
  7359. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7360. screenshotCanvas.toBlob = function (callback, type, quality) {
  7361. var _this = this;
  7362. setTimeout(function () {
  7363. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7364. for (var i = 0; i < len; i++) {
  7365. arr[i] = binStr.charCodeAt(i);
  7366. }
  7367. callback(new Blob([arr], { type: type || 'image/png' }));
  7368. });
  7369. };
  7370. }
  7371. screenshotCanvas.toBlob(function (blob) {
  7372. var url = URL.createObjectURL(blob);
  7373. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7374. if (("download" in document.createElement("a"))) {
  7375. var a = window.document.createElement("a");
  7376. a.href = url;
  7377. if (fileName) {
  7378. a.setAttribute("download", fileName);
  7379. }
  7380. else {
  7381. var date = new Date();
  7382. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7383. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7384. }
  7385. window.document.body.appendChild(a);
  7386. a.addEventListener("click", function () {
  7387. if (a.parentElement) {
  7388. a.parentElement.removeChild(a);
  7389. }
  7390. });
  7391. a.click();
  7392. }
  7393. else {
  7394. var newWindow = window.open("");
  7395. if (!newWindow)
  7396. return;
  7397. var img = newWindow.document.createElement("img");
  7398. img.onload = function () {
  7399. // no longer need to read the blob so it's revoked
  7400. URL.revokeObjectURL(url);
  7401. };
  7402. img.src = url;
  7403. newWindow.document.body.appendChild(img);
  7404. }
  7405. });
  7406. }
  7407. };
  7408. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7409. if (mimeType === void 0) { mimeType = "image/png"; }
  7410. var width;
  7411. var height;
  7412. // If a precision value is specified
  7413. if (size.precision) {
  7414. width = Math.round(engine.getRenderWidth() * size.precision);
  7415. height = Math.round(width / engine.getAspectRatio(camera));
  7416. }
  7417. else if (size.width && size.height) {
  7418. width = size.width;
  7419. height = size.height;
  7420. }
  7421. else if (size.width && !size.height) {
  7422. width = size.width;
  7423. height = Math.round(width / engine.getAspectRatio(camera));
  7424. }
  7425. else if (size.height && !size.width) {
  7426. height = size.height;
  7427. width = Math.round(height * engine.getAspectRatio(camera));
  7428. }
  7429. else if (!isNaN(size)) {
  7430. height = size;
  7431. width = size;
  7432. }
  7433. else {
  7434. Tools.Error("Invalid 'size' parameter !");
  7435. return;
  7436. }
  7437. if (!screenshotCanvas) {
  7438. screenshotCanvas = document.createElement('canvas');
  7439. }
  7440. screenshotCanvas.width = width;
  7441. screenshotCanvas.height = height;
  7442. var renderContext = screenshotCanvas.getContext("2d");
  7443. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7444. var newWidth = width;
  7445. var newHeight = newWidth / ratio;
  7446. if (newHeight > height) {
  7447. newHeight = height;
  7448. newWidth = newHeight * ratio;
  7449. }
  7450. var offsetX = Math.max(0, width - newWidth) / 2;
  7451. var offsetY = Math.max(0, height - newHeight) / 2;
  7452. var renderingCanvas = engine.getRenderingCanvas();
  7453. if (renderContext && renderingCanvas) {
  7454. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7455. }
  7456. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7457. };
  7458. /**
  7459. * Generates an image screenshot from the specified camera.
  7460. *
  7461. * @param engine The engine to use for rendering
  7462. * @param camera The camera to use for rendering
  7463. * @param size This parameter can be set to a single number or to an object with the
  7464. * following (optional) properties: precision, width, height. If a single number is passed,
  7465. * it will be used for both width and height. If an object is passed, the screenshot size
  7466. * will be derived from the parameters. The precision property is a multiplier allowing
  7467. * rendering at a higher or lower resolution.
  7468. * @param successCallback The callback receives a single parameter which contains the
  7469. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7470. * src parameter of an <img> to display it.
  7471. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7472. * Check your browser for supported MIME types.
  7473. * @param samples Texture samples (default: 1)
  7474. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7475. * @param fileName A name for for the downloaded file.
  7476. * @constructor
  7477. */
  7478. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7479. if (mimeType === void 0) { mimeType = "image/png"; }
  7480. if (samples === void 0) { samples = 1; }
  7481. if (antialiasing === void 0) { antialiasing = false; }
  7482. var width;
  7483. var height;
  7484. //If a precision value is specified
  7485. if (size.precision) {
  7486. width = Math.round(engine.getRenderWidth() * size.precision);
  7487. height = Math.round(width / engine.getAspectRatio(camera));
  7488. size = { width: width, height: height };
  7489. }
  7490. else if (size.width && size.height) {
  7491. width = size.width;
  7492. height = size.height;
  7493. }
  7494. else if (size.width && !size.height) {
  7495. width = size.width;
  7496. height = Math.round(width / engine.getAspectRatio(camera));
  7497. size = { width: width, height: height };
  7498. }
  7499. else if (size.height && !size.width) {
  7500. height = size.height;
  7501. width = Math.round(height * engine.getAspectRatio(camera));
  7502. size = { width: width, height: height };
  7503. }
  7504. else if (!isNaN(size)) {
  7505. height = size;
  7506. width = size;
  7507. }
  7508. else {
  7509. Tools.Error("Invalid 'size' parameter !");
  7510. return;
  7511. }
  7512. var scene = camera.getScene();
  7513. var previousCamera = null;
  7514. if (scene.activeCamera !== camera) {
  7515. previousCamera = scene.activeCamera;
  7516. scene.activeCamera = camera;
  7517. }
  7518. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7519. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7520. texture.renderList = null;
  7521. texture.samples = samples;
  7522. if (antialiasing) {
  7523. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7524. }
  7525. texture.onAfterRenderObservable.add(function () {
  7526. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7527. });
  7528. scene.incrementRenderId();
  7529. scene.resetCachedMaterial();
  7530. texture.render(true);
  7531. texture.dispose();
  7532. if (previousCamera) {
  7533. scene.activeCamera = previousCamera;
  7534. }
  7535. camera.getProjectionMatrix(true); // Force cache refresh;
  7536. };
  7537. // XHR response validator for local file scenario
  7538. Tools.ValidateXHRData = function (xhr, dataType) {
  7539. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7540. if (dataType === void 0) { dataType = 7; }
  7541. try {
  7542. if (dataType & 1) {
  7543. if (xhr.responseText && xhr.responseText.length > 0) {
  7544. return true;
  7545. }
  7546. else if (dataType === 1) {
  7547. return false;
  7548. }
  7549. }
  7550. if (dataType & 2) {
  7551. // Check header width and height since there is no "TGA" magic number
  7552. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7553. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7554. return true;
  7555. }
  7556. else if (dataType === 2) {
  7557. return false;
  7558. }
  7559. }
  7560. if (dataType & 4) {
  7561. // Check for the "DDS" magic number
  7562. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7563. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7564. return true;
  7565. }
  7566. else {
  7567. return false;
  7568. }
  7569. }
  7570. }
  7571. catch (e) {
  7572. // Global protection
  7573. }
  7574. return false;
  7575. };
  7576. /**
  7577. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7578. * Be aware Math.random() could cause collisions, but:
  7579. * "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"
  7580. */
  7581. Tools.RandomId = function () {
  7582. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7583. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7584. return v.toString(16);
  7585. });
  7586. };
  7587. Object.defineProperty(Tools, "NoneLogLevel", {
  7588. get: function () {
  7589. return Tools._NoneLogLevel;
  7590. },
  7591. enumerable: true,
  7592. configurable: true
  7593. });
  7594. Object.defineProperty(Tools, "MessageLogLevel", {
  7595. get: function () {
  7596. return Tools._MessageLogLevel;
  7597. },
  7598. enumerable: true,
  7599. configurable: true
  7600. });
  7601. Object.defineProperty(Tools, "WarningLogLevel", {
  7602. get: function () {
  7603. return Tools._WarningLogLevel;
  7604. },
  7605. enumerable: true,
  7606. configurable: true
  7607. });
  7608. Object.defineProperty(Tools, "ErrorLogLevel", {
  7609. get: function () {
  7610. return Tools._ErrorLogLevel;
  7611. },
  7612. enumerable: true,
  7613. configurable: true
  7614. });
  7615. Object.defineProperty(Tools, "AllLogLevel", {
  7616. get: function () {
  7617. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7618. },
  7619. enumerable: true,
  7620. configurable: true
  7621. });
  7622. Tools._AddLogEntry = function (entry) {
  7623. Tools._LogCache = entry + Tools._LogCache;
  7624. if (Tools.OnNewCacheEntry) {
  7625. Tools.OnNewCacheEntry(entry);
  7626. }
  7627. };
  7628. Tools._FormatMessage = function (message) {
  7629. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7630. var date = new Date();
  7631. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7632. };
  7633. Tools._LogDisabled = function (message) {
  7634. // nothing to do
  7635. };
  7636. Tools._LogEnabled = function (message) {
  7637. var formattedMessage = Tools._FormatMessage(message);
  7638. console.log("BJS - " + formattedMessage);
  7639. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7640. Tools._AddLogEntry(entry);
  7641. };
  7642. Tools._WarnDisabled = function (message) {
  7643. // nothing to do
  7644. };
  7645. Tools._WarnEnabled = function (message) {
  7646. var formattedMessage = Tools._FormatMessage(message);
  7647. console.warn("BJS - " + formattedMessage);
  7648. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7649. Tools._AddLogEntry(entry);
  7650. };
  7651. Tools._ErrorDisabled = function (message) {
  7652. // nothing to do
  7653. };
  7654. Tools._ErrorEnabled = function (message) {
  7655. Tools.errorsCount++;
  7656. var formattedMessage = Tools._FormatMessage(message);
  7657. console.error("BJS - " + formattedMessage);
  7658. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7659. Tools._AddLogEntry(entry);
  7660. };
  7661. Object.defineProperty(Tools, "LogCache", {
  7662. get: function () {
  7663. return Tools._LogCache;
  7664. },
  7665. enumerable: true,
  7666. configurable: true
  7667. });
  7668. Tools.ClearLogCache = function () {
  7669. Tools._LogCache = "";
  7670. Tools.errorsCount = 0;
  7671. };
  7672. Object.defineProperty(Tools, "LogLevels", {
  7673. set: function (level) {
  7674. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7675. Tools.Log = Tools._LogEnabled;
  7676. }
  7677. else {
  7678. Tools.Log = Tools._LogDisabled;
  7679. }
  7680. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7681. Tools.Warn = Tools._WarnEnabled;
  7682. }
  7683. else {
  7684. Tools.Warn = Tools._WarnDisabled;
  7685. }
  7686. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7687. Tools.Error = Tools._ErrorEnabled;
  7688. }
  7689. else {
  7690. Tools.Error = Tools._ErrorDisabled;
  7691. }
  7692. },
  7693. enumerable: true,
  7694. configurable: true
  7695. });
  7696. Tools.IsWindowObjectExist = function () {
  7697. return (typeof window) !== "undefined";
  7698. };
  7699. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  7700. get: function () {
  7701. return Tools._PerformanceNoneLogLevel;
  7702. },
  7703. enumerable: true,
  7704. configurable: true
  7705. });
  7706. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  7707. get: function () {
  7708. return Tools._PerformanceUserMarkLogLevel;
  7709. },
  7710. enumerable: true,
  7711. configurable: true
  7712. });
  7713. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  7714. get: function () {
  7715. return Tools._PerformanceConsoleLogLevel;
  7716. },
  7717. enumerable: true,
  7718. configurable: true
  7719. });
  7720. Object.defineProperty(Tools, "PerformanceLogLevel", {
  7721. set: function (level) {
  7722. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  7723. Tools.StartPerformanceCounter = Tools._StartUserMark;
  7724. Tools.EndPerformanceCounter = Tools._EndUserMark;
  7725. return;
  7726. }
  7727. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  7728. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  7729. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  7730. return;
  7731. }
  7732. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7733. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7734. },
  7735. enumerable: true,
  7736. configurable: true
  7737. });
  7738. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  7739. };
  7740. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  7741. };
  7742. Tools._StartUserMark = function (counterName, condition) {
  7743. if (condition === void 0) { condition = true; }
  7744. if (!Tools._performance) {
  7745. if (!Tools.IsWindowObjectExist()) {
  7746. return;
  7747. }
  7748. Tools._performance = window.performance;
  7749. }
  7750. if (!condition || !Tools._performance.mark) {
  7751. return;
  7752. }
  7753. Tools._performance.mark(counterName + "-Begin");
  7754. };
  7755. Tools._EndUserMark = function (counterName, condition) {
  7756. if (condition === void 0) { condition = true; }
  7757. if (!condition || !Tools._performance.mark) {
  7758. return;
  7759. }
  7760. Tools._performance.mark(counterName + "-End");
  7761. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  7762. };
  7763. Tools._StartPerformanceConsole = function (counterName, condition) {
  7764. if (condition === void 0) { condition = true; }
  7765. if (!condition) {
  7766. return;
  7767. }
  7768. Tools._StartUserMark(counterName, condition);
  7769. if (console.time) {
  7770. console.time(counterName);
  7771. }
  7772. };
  7773. Tools._EndPerformanceConsole = function (counterName, condition) {
  7774. if (condition === void 0) { condition = true; }
  7775. if (!condition) {
  7776. return;
  7777. }
  7778. Tools._EndUserMark(counterName, condition);
  7779. if (console.time) {
  7780. console.timeEnd(counterName);
  7781. }
  7782. };
  7783. Object.defineProperty(Tools, "Now", {
  7784. get: function () {
  7785. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  7786. return window.performance.now();
  7787. }
  7788. return new Date().getTime();
  7789. },
  7790. enumerable: true,
  7791. configurable: true
  7792. });
  7793. /**
  7794. * This method will return the name of the class used to create the instance of the given object.
  7795. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  7796. * @param object the object to get the class name from
  7797. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  7798. */
  7799. Tools.GetClassName = function (object, isType) {
  7800. if (isType === void 0) { isType = false; }
  7801. var name = null;
  7802. if (!isType && object.getClassName) {
  7803. name = object.getClassName();
  7804. }
  7805. else {
  7806. if (object instanceof Object) {
  7807. var classObj = isType ? object : Object.getPrototypeOf(object);
  7808. name = classObj.constructor["__bjsclassName__"];
  7809. }
  7810. if (!name) {
  7811. name = typeof object;
  7812. }
  7813. }
  7814. return name;
  7815. };
  7816. Tools.First = function (array, predicate) {
  7817. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7818. var el = array_1[_i];
  7819. if (predicate(el)) {
  7820. return el;
  7821. }
  7822. }
  7823. return null;
  7824. };
  7825. /**
  7826. * This method will return the name of the full name of the class, including its owning module (if any).
  7827. * 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).
  7828. * @param object the object to get the class name from
  7829. * @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.
  7830. */
  7831. Tools.getFullClassName = function (object, isType) {
  7832. if (isType === void 0) { isType = false; }
  7833. var className = null;
  7834. var moduleName = null;
  7835. if (!isType && object.getClassName) {
  7836. className = object.getClassName();
  7837. }
  7838. else {
  7839. if (object instanceof Object) {
  7840. var classObj = isType ? object : Object.getPrototypeOf(object);
  7841. className = classObj.constructor["__bjsclassName__"];
  7842. moduleName = classObj.constructor["__bjsmoduleName__"];
  7843. }
  7844. if (!className) {
  7845. className = typeof object;
  7846. }
  7847. }
  7848. if (!className) {
  7849. return null;
  7850. }
  7851. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7852. };
  7853. /**
  7854. * 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.
  7855. * @param array
  7856. */
  7857. Tools.arrayOrStringFeeder = function (array) {
  7858. return function (index) {
  7859. if (index >= array.length) {
  7860. return null;
  7861. }
  7862. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7863. if (val && val.getHashCode) {
  7864. val = val.getHashCode();
  7865. }
  7866. if (typeof val === "string") {
  7867. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7868. }
  7869. return val;
  7870. };
  7871. };
  7872. /**
  7873. * Compute the hashCode of a stream of number
  7874. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7875. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7876. * @return the hash code computed
  7877. */
  7878. Tools.hashCodeFromStream = function (feeder) {
  7879. // Based from here: http://stackoverflow.com/a/7616484/802124
  7880. var hash = 0;
  7881. var index = 0;
  7882. var chr = feeder(index++);
  7883. while (chr != null) {
  7884. hash = ((hash << 5) - hash) + chr;
  7885. hash |= 0; // Convert to 32bit integer
  7886. chr = feeder(index++);
  7887. }
  7888. return hash;
  7889. };
  7890. Tools.BaseUrl = "";
  7891. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7892. /**
  7893. * Default behaviour for cors in the application.
  7894. * It can be a string if the expected behavior is identical in the entire app.
  7895. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7896. */
  7897. Tools.CorsBehavior = "anonymous";
  7898. Tools.UseFallbackTexture = true;
  7899. /**
  7900. * Use this object to register external classes like custom textures or material
  7901. * to allow the laoders to instantiate them
  7902. */
  7903. Tools.RegisteredExternalClasses = {};
  7904. // Used in case of a texture loading problem
  7905. 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";
  7906. Tools.PreprocessUrl = function (url) {
  7907. return url;
  7908. };
  7909. // Logs
  7910. Tools._NoneLogLevel = 0;
  7911. Tools._MessageLogLevel = 1;
  7912. Tools._WarningLogLevel = 2;
  7913. Tools._ErrorLogLevel = 4;
  7914. Tools._LogCache = "";
  7915. Tools.errorsCount = 0;
  7916. Tools.Log = Tools._LogEnabled;
  7917. Tools.Warn = Tools._WarnEnabled;
  7918. Tools.Error = Tools._ErrorEnabled;
  7919. // Performances
  7920. Tools._PerformanceNoneLogLevel = 0;
  7921. Tools._PerformanceUserMarkLogLevel = 1;
  7922. Tools._PerformanceConsoleLogLevel = 2;
  7923. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7924. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7925. return Tools;
  7926. }());
  7927. BABYLON.Tools = Tools;
  7928. /**
  7929. * This class is used to track a performance counter which is number based.
  7930. * The user has access to many properties which give statistics of different nature
  7931. *
  7932. * The implementer can track two kinds of Performance Counter: time and count
  7933. * 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.
  7934. * 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.
  7935. */
  7936. var PerfCounter = /** @class */ (function () {
  7937. function PerfCounter() {
  7938. this._startMonitoringTime = 0;
  7939. this._min = 0;
  7940. this._max = 0;
  7941. this._average = 0;
  7942. this._lastSecAverage = 0;
  7943. this._current = 0;
  7944. this._totalValueCount = 0;
  7945. this._totalAccumulated = 0;
  7946. this._lastSecAccumulated = 0;
  7947. this._lastSecTime = 0;
  7948. this._lastSecValueCount = 0;
  7949. }
  7950. Object.defineProperty(PerfCounter.prototype, "min", {
  7951. /**
  7952. * Returns the smallest value ever
  7953. */
  7954. get: function () {
  7955. return this._min;
  7956. },
  7957. enumerable: true,
  7958. configurable: true
  7959. });
  7960. Object.defineProperty(PerfCounter.prototype, "max", {
  7961. /**
  7962. * Returns the biggest value ever
  7963. */
  7964. get: function () {
  7965. return this._max;
  7966. },
  7967. enumerable: true,
  7968. configurable: true
  7969. });
  7970. Object.defineProperty(PerfCounter.prototype, "average", {
  7971. /**
  7972. * Returns the average value since the performance counter is running
  7973. */
  7974. get: function () {
  7975. return this._average;
  7976. },
  7977. enumerable: true,
  7978. configurable: true
  7979. });
  7980. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7981. /**
  7982. * Returns the average value of the last second the counter was monitored
  7983. */
  7984. get: function () {
  7985. return this._lastSecAverage;
  7986. },
  7987. enumerable: true,
  7988. configurable: true
  7989. });
  7990. Object.defineProperty(PerfCounter.prototype, "current", {
  7991. /**
  7992. * Returns the current value
  7993. */
  7994. get: function () {
  7995. return this._current;
  7996. },
  7997. enumerable: true,
  7998. configurable: true
  7999. });
  8000. Object.defineProperty(PerfCounter.prototype, "total", {
  8001. get: function () {
  8002. return this._totalAccumulated;
  8003. },
  8004. enumerable: true,
  8005. configurable: true
  8006. });
  8007. Object.defineProperty(PerfCounter.prototype, "count", {
  8008. get: function () {
  8009. return this._totalValueCount;
  8010. },
  8011. enumerable: true,
  8012. configurable: true
  8013. });
  8014. /**
  8015. * Call this method to start monitoring a new frame.
  8016. * 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.
  8017. */
  8018. PerfCounter.prototype.fetchNewFrame = function () {
  8019. this._totalValueCount++;
  8020. this._current = 0;
  8021. this._lastSecValueCount++;
  8022. };
  8023. /**
  8024. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8025. * @param newCount the count value to add to the monitored count
  8026. * @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.
  8027. */
  8028. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8029. if (!PerfCounter.Enabled) {
  8030. return;
  8031. }
  8032. this._current += newCount;
  8033. if (fetchResult) {
  8034. this._fetchResult();
  8035. }
  8036. };
  8037. /**
  8038. * Start monitoring this performance counter
  8039. */
  8040. PerfCounter.prototype.beginMonitoring = function () {
  8041. if (!PerfCounter.Enabled) {
  8042. return;
  8043. }
  8044. this._startMonitoringTime = Tools.Now;
  8045. };
  8046. /**
  8047. * Compute the time lapsed since the previous beginMonitoring() call.
  8048. * @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
  8049. */
  8050. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8051. if (newFrame === void 0) { newFrame = true; }
  8052. if (!PerfCounter.Enabled) {
  8053. return;
  8054. }
  8055. if (newFrame) {
  8056. this.fetchNewFrame();
  8057. }
  8058. var currentTime = Tools.Now;
  8059. this._current = currentTime - this._startMonitoringTime;
  8060. if (newFrame) {
  8061. this._fetchResult();
  8062. }
  8063. };
  8064. PerfCounter.prototype._fetchResult = function () {
  8065. this._totalAccumulated += this._current;
  8066. this._lastSecAccumulated += this._current;
  8067. // Min/Max update
  8068. this._min = Math.min(this._min, this._current);
  8069. this._max = Math.max(this._max, this._current);
  8070. this._average = this._totalAccumulated / this._totalValueCount;
  8071. // Reset last sec?
  8072. var now = Tools.Now;
  8073. if ((now - this._lastSecTime) > 1000) {
  8074. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8075. this._lastSecTime = now;
  8076. this._lastSecAccumulated = 0;
  8077. this._lastSecValueCount = 0;
  8078. }
  8079. };
  8080. PerfCounter.Enabled = true;
  8081. return PerfCounter;
  8082. }());
  8083. BABYLON.PerfCounter = PerfCounter;
  8084. /**
  8085. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8086. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8087. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8088. * @param name The name of the class, case should be preserved
  8089. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8090. */
  8091. function className(name, module) {
  8092. return function (target) {
  8093. target["__bjsclassName__"] = name;
  8094. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8095. };
  8096. }
  8097. BABYLON.className = className;
  8098. /**
  8099. * An implementation of a loop for asynchronous functions.
  8100. */
  8101. var AsyncLoop = /** @class */ (function () {
  8102. /**
  8103. * Constroctor.
  8104. * @param iterations the number of iterations.
  8105. * @param _fn the function to run each iteration
  8106. * @param _successCallback the callback that will be called upon succesful execution
  8107. * @param offset starting offset.
  8108. */
  8109. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8110. if (offset === void 0) { offset = 0; }
  8111. this.iterations = iterations;
  8112. this._fn = _fn;
  8113. this._successCallback = _successCallback;
  8114. this.index = offset - 1;
  8115. this._done = false;
  8116. }
  8117. /**
  8118. * Execute the next iteration. Must be called after the last iteration was finished.
  8119. */
  8120. AsyncLoop.prototype.executeNext = function () {
  8121. if (!this._done) {
  8122. if (this.index + 1 < this.iterations) {
  8123. ++this.index;
  8124. this._fn(this);
  8125. }
  8126. else {
  8127. this.breakLoop();
  8128. }
  8129. }
  8130. };
  8131. /**
  8132. * Break the loop and run the success callback.
  8133. */
  8134. AsyncLoop.prototype.breakLoop = function () {
  8135. this._done = true;
  8136. this._successCallback();
  8137. };
  8138. /**
  8139. * Helper function
  8140. */
  8141. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8142. if (offset === void 0) { offset = 0; }
  8143. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8144. loop.executeNext();
  8145. return loop;
  8146. };
  8147. /**
  8148. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8149. * @param iterations total number of iterations
  8150. * @param syncedIterations number of synchronous iterations in each async iteration.
  8151. * @param fn the function to call each iteration.
  8152. * @param callback a success call back that will be called when iterating stops.
  8153. * @param breakFunction a break condition (optional)
  8154. * @param timeout timeout settings for the setTimeout function. default - 0.
  8155. * @constructor
  8156. */
  8157. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8158. if (timeout === void 0) { timeout = 0; }
  8159. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8160. if (breakFunction && breakFunction())
  8161. loop.breakLoop();
  8162. else {
  8163. setTimeout(function () {
  8164. for (var i = 0; i < syncedIterations; ++i) {
  8165. var iteration = (loop.index * syncedIterations) + i;
  8166. if (iteration >= iterations)
  8167. break;
  8168. fn(iteration);
  8169. if (breakFunction && breakFunction()) {
  8170. loop.breakLoop();
  8171. break;
  8172. }
  8173. }
  8174. loop.executeNext();
  8175. }, timeout);
  8176. }
  8177. }, callback);
  8178. };
  8179. return AsyncLoop;
  8180. }());
  8181. BABYLON.AsyncLoop = AsyncLoop;
  8182. })(BABYLON || (BABYLON = {}));
  8183. //# sourceMappingURL=babylon.tools.js.map
  8184. var BABYLON;
  8185. (function (BABYLON) {
  8186. var _AlphaState = /** @class */ (function () {
  8187. /**
  8188. * Initializes the state.
  8189. */
  8190. function _AlphaState() {
  8191. this._isAlphaBlendDirty = false;
  8192. this._isBlendFunctionParametersDirty = false;
  8193. this._isBlendEquationParametersDirty = false;
  8194. this._isBlendConstantsDirty = false;
  8195. this._alphaBlend = false;
  8196. this._blendFunctionParameters = new Array(4);
  8197. this._blendEquationParameters = new Array(2);
  8198. this._blendConstants = new Array(4);
  8199. this.reset();
  8200. }
  8201. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8202. get: function () {
  8203. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8204. },
  8205. enumerable: true,
  8206. configurable: true
  8207. });
  8208. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8209. get: function () {
  8210. return this._alphaBlend;
  8211. },
  8212. set: function (value) {
  8213. if (this._alphaBlend === value) {
  8214. return;
  8215. }
  8216. this._alphaBlend = value;
  8217. this._isAlphaBlendDirty = true;
  8218. },
  8219. enumerable: true,
  8220. configurable: true
  8221. });
  8222. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8223. if (this._blendConstants[0] === r &&
  8224. this._blendConstants[1] === g &&
  8225. this._blendConstants[2] === b &&
  8226. this._blendConstants[3] === a) {
  8227. return;
  8228. }
  8229. this._blendConstants[0] = r;
  8230. this._blendConstants[1] = g;
  8231. this._blendConstants[2] = b;
  8232. this._blendConstants[3] = a;
  8233. this._isBlendConstantsDirty = true;
  8234. };
  8235. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8236. if (this._blendFunctionParameters[0] === value0 &&
  8237. this._blendFunctionParameters[1] === value1 &&
  8238. this._blendFunctionParameters[2] === value2 &&
  8239. this._blendFunctionParameters[3] === value3) {
  8240. return;
  8241. }
  8242. this._blendFunctionParameters[0] = value0;
  8243. this._blendFunctionParameters[1] = value1;
  8244. this._blendFunctionParameters[2] = value2;
  8245. this._blendFunctionParameters[3] = value3;
  8246. this._isBlendFunctionParametersDirty = true;
  8247. };
  8248. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8249. if (this._blendEquationParameters[0] === rgb &&
  8250. this._blendEquationParameters[1] === alpha) {
  8251. return;
  8252. }
  8253. this._blendEquationParameters[0] = rgb;
  8254. this._blendEquationParameters[1] = alpha;
  8255. this._isBlendEquationParametersDirty = true;
  8256. };
  8257. _AlphaState.prototype.reset = function () {
  8258. this._alphaBlend = false;
  8259. this._blendFunctionParameters[0] = null;
  8260. this._blendFunctionParameters[1] = null;
  8261. this._blendFunctionParameters[2] = null;
  8262. this._blendFunctionParameters[3] = null;
  8263. this._blendEquationParameters[0] = null;
  8264. this._blendEquationParameters[1] = null;
  8265. this._blendConstants[0] = null;
  8266. this._blendConstants[1] = null;
  8267. this._blendConstants[2] = null;
  8268. this._blendConstants[3] = null;
  8269. this._isAlphaBlendDirty = true;
  8270. this._isBlendFunctionParametersDirty = false;
  8271. this._isBlendEquationParametersDirty = false;
  8272. this._isBlendConstantsDirty = false;
  8273. };
  8274. _AlphaState.prototype.apply = function (gl) {
  8275. if (!this.isDirty) {
  8276. return;
  8277. }
  8278. // Alpha blend
  8279. if (this._isAlphaBlendDirty) {
  8280. if (this._alphaBlend) {
  8281. gl.enable(gl.BLEND);
  8282. }
  8283. else {
  8284. gl.disable(gl.BLEND);
  8285. }
  8286. this._isAlphaBlendDirty = false;
  8287. }
  8288. // Alpha function
  8289. if (this._isBlendFunctionParametersDirty) {
  8290. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8291. this._isBlendFunctionParametersDirty = false;
  8292. }
  8293. // Alpha equation
  8294. if (this._isBlendEquationParametersDirty) {
  8295. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8296. this._isBlendEquationParametersDirty = false;
  8297. }
  8298. // Constants
  8299. if (this._isBlendConstantsDirty) {
  8300. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8301. this._isBlendConstantsDirty = false;
  8302. }
  8303. };
  8304. return _AlphaState;
  8305. }());
  8306. BABYLON._AlphaState = _AlphaState;
  8307. })(BABYLON || (BABYLON = {}));
  8308. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8309. var BABYLON;
  8310. (function (BABYLON) {
  8311. var _DepthCullingState = /** @class */ (function () {
  8312. /**
  8313. * Initializes the state.
  8314. */
  8315. function _DepthCullingState() {
  8316. this._isDepthTestDirty = false;
  8317. this._isDepthMaskDirty = false;
  8318. this._isDepthFuncDirty = false;
  8319. this._isCullFaceDirty = false;
  8320. this._isCullDirty = false;
  8321. this._isZOffsetDirty = false;
  8322. this._isFrontFaceDirty = false;
  8323. this.reset();
  8324. }
  8325. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8326. get: function () {
  8327. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8328. },
  8329. enumerable: true,
  8330. configurable: true
  8331. });
  8332. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8333. get: function () {
  8334. return this._zOffset;
  8335. },
  8336. set: function (value) {
  8337. if (this._zOffset === value) {
  8338. return;
  8339. }
  8340. this._zOffset = value;
  8341. this._isZOffsetDirty = true;
  8342. },
  8343. enumerable: true,
  8344. configurable: true
  8345. });
  8346. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8347. get: function () {
  8348. return this._cullFace;
  8349. },
  8350. set: function (value) {
  8351. if (this._cullFace === value) {
  8352. return;
  8353. }
  8354. this._cullFace = value;
  8355. this._isCullFaceDirty = true;
  8356. },
  8357. enumerable: true,
  8358. configurable: true
  8359. });
  8360. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8361. get: function () {
  8362. return this._cull;
  8363. },
  8364. set: function (value) {
  8365. if (this._cull === value) {
  8366. return;
  8367. }
  8368. this._cull = value;
  8369. this._isCullDirty = true;
  8370. },
  8371. enumerable: true,
  8372. configurable: true
  8373. });
  8374. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8375. get: function () {
  8376. return this._depthFunc;
  8377. },
  8378. set: function (value) {
  8379. if (this._depthFunc === value) {
  8380. return;
  8381. }
  8382. this._depthFunc = value;
  8383. this._isDepthFuncDirty = true;
  8384. },
  8385. enumerable: true,
  8386. configurable: true
  8387. });
  8388. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8389. get: function () {
  8390. return this._depthMask;
  8391. },
  8392. set: function (value) {
  8393. if (this._depthMask === value) {
  8394. return;
  8395. }
  8396. this._depthMask = value;
  8397. this._isDepthMaskDirty = true;
  8398. },
  8399. enumerable: true,
  8400. configurable: true
  8401. });
  8402. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8403. get: function () {
  8404. return this._depthTest;
  8405. },
  8406. set: function (value) {
  8407. if (this._depthTest === value) {
  8408. return;
  8409. }
  8410. this._depthTest = value;
  8411. this._isDepthTestDirty = true;
  8412. },
  8413. enumerable: true,
  8414. configurable: true
  8415. });
  8416. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8417. get: function () {
  8418. return this._frontFace;
  8419. },
  8420. set: function (value) {
  8421. if (this._frontFace === value) {
  8422. return;
  8423. }
  8424. this._frontFace = value;
  8425. this._isFrontFaceDirty = true;
  8426. },
  8427. enumerable: true,
  8428. configurable: true
  8429. });
  8430. _DepthCullingState.prototype.reset = function () {
  8431. this._depthMask = true;
  8432. this._depthTest = true;
  8433. this._depthFunc = null;
  8434. this._cullFace = null;
  8435. this._cull = null;
  8436. this._zOffset = 0;
  8437. this._frontFace = null;
  8438. this._isDepthTestDirty = true;
  8439. this._isDepthMaskDirty = true;
  8440. this._isDepthFuncDirty = false;
  8441. this._isCullFaceDirty = false;
  8442. this._isCullDirty = false;
  8443. this._isZOffsetDirty = false;
  8444. this._isFrontFaceDirty = false;
  8445. };
  8446. _DepthCullingState.prototype.apply = function (gl) {
  8447. if (!this.isDirty) {
  8448. return;
  8449. }
  8450. // Cull
  8451. if (this._isCullDirty) {
  8452. if (this.cull) {
  8453. gl.enable(gl.CULL_FACE);
  8454. }
  8455. else {
  8456. gl.disable(gl.CULL_FACE);
  8457. }
  8458. this._isCullDirty = false;
  8459. }
  8460. // Cull face
  8461. if (this._isCullFaceDirty) {
  8462. gl.cullFace(this.cullFace);
  8463. this._isCullFaceDirty = false;
  8464. }
  8465. // Depth mask
  8466. if (this._isDepthMaskDirty) {
  8467. gl.depthMask(this.depthMask);
  8468. this._isDepthMaskDirty = false;
  8469. }
  8470. // Depth test
  8471. if (this._isDepthTestDirty) {
  8472. if (this.depthTest) {
  8473. gl.enable(gl.DEPTH_TEST);
  8474. }
  8475. else {
  8476. gl.disable(gl.DEPTH_TEST);
  8477. }
  8478. this._isDepthTestDirty = false;
  8479. }
  8480. // Depth func
  8481. if (this._isDepthFuncDirty) {
  8482. gl.depthFunc(this.depthFunc);
  8483. this._isDepthFuncDirty = false;
  8484. }
  8485. // zOffset
  8486. if (this._isZOffsetDirty) {
  8487. if (this.zOffset) {
  8488. gl.enable(gl.POLYGON_OFFSET_FILL);
  8489. gl.polygonOffset(this.zOffset, 0);
  8490. }
  8491. else {
  8492. gl.disable(gl.POLYGON_OFFSET_FILL);
  8493. }
  8494. this._isZOffsetDirty = false;
  8495. }
  8496. // Front face
  8497. if (this._isFrontFaceDirty) {
  8498. gl.frontFace(this.frontFace);
  8499. this._isFrontFaceDirty = false;
  8500. }
  8501. };
  8502. return _DepthCullingState;
  8503. }());
  8504. BABYLON._DepthCullingState = _DepthCullingState;
  8505. })(BABYLON || (BABYLON = {}));
  8506. //# sourceMappingURL=babylon.depthCullingState.js.map
  8507. var BABYLON;
  8508. (function (BABYLON) {
  8509. var _StencilState = /** @class */ (function () {
  8510. function _StencilState() {
  8511. this._isStencilTestDirty = false;
  8512. this._isStencilMaskDirty = false;
  8513. this._isStencilFuncDirty = false;
  8514. this._isStencilOpDirty = false;
  8515. this.reset();
  8516. }
  8517. Object.defineProperty(_StencilState.prototype, "isDirty", {
  8518. get: function () {
  8519. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  8520. },
  8521. enumerable: true,
  8522. configurable: true
  8523. });
  8524. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  8525. get: function () {
  8526. return this._stencilFunc;
  8527. },
  8528. set: function (value) {
  8529. if (this._stencilFunc === value) {
  8530. return;
  8531. }
  8532. this._stencilFunc = value;
  8533. this._isStencilFuncDirty = true;
  8534. },
  8535. enumerable: true,
  8536. configurable: true
  8537. });
  8538. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  8539. get: function () {
  8540. return this._stencilFuncRef;
  8541. },
  8542. set: function (value) {
  8543. if (this._stencilFuncRef === value) {
  8544. return;
  8545. }
  8546. this._stencilFuncRef = value;
  8547. this._isStencilFuncDirty = true;
  8548. },
  8549. enumerable: true,
  8550. configurable: true
  8551. });
  8552. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  8553. get: function () {
  8554. return this._stencilFuncMask;
  8555. },
  8556. set: function (value) {
  8557. if (this._stencilFuncMask === value) {
  8558. return;
  8559. }
  8560. this._stencilFuncMask = value;
  8561. this._isStencilFuncDirty = true;
  8562. },
  8563. enumerable: true,
  8564. configurable: true
  8565. });
  8566. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  8567. get: function () {
  8568. return this._stencilOpStencilFail;
  8569. },
  8570. set: function (value) {
  8571. if (this._stencilOpStencilFail === value) {
  8572. return;
  8573. }
  8574. this._stencilOpStencilFail = value;
  8575. this._isStencilOpDirty = true;
  8576. },
  8577. enumerable: true,
  8578. configurable: true
  8579. });
  8580. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  8581. get: function () {
  8582. return this._stencilOpDepthFail;
  8583. },
  8584. set: function (value) {
  8585. if (this._stencilOpDepthFail === value) {
  8586. return;
  8587. }
  8588. this._stencilOpDepthFail = value;
  8589. this._isStencilOpDirty = true;
  8590. },
  8591. enumerable: true,
  8592. configurable: true
  8593. });
  8594. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  8595. get: function () {
  8596. return this._stencilOpStencilDepthPass;
  8597. },
  8598. set: function (value) {
  8599. if (this._stencilOpStencilDepthPass === value) {
  8600. return;
  8601. }
  8602. this._stencilOpStencilDepthPass = value;
  8603. this._isStencilOpDirty = true;
  8604. },
  8605. enumerable: true,
  8606. configurable: true
  8607. });
  8608. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  8609. get: function () {
  8610. return this._stencilMask;
  8611. },
  8612. set: function (value) {
  8613. if (this._stencilMask === value) {
  8614. return;
  8615. }
  8616. this._stencilMask = value;
  8617. this._isStencilMaskDirty = true;
  8618. },
  8619. enumerable: true,
  8620. configurable: true
  8621. });
  8622. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  8623. get: function () {
  8624. return this._stencilTest;
  8625. },
  8626. set: function (value) {
  8627. if (this._stencilTest === value) {
  8628. return;
  8629. }
  8630. this._stencilTest = value;
  8631. this._isStencilTestDirty = true;
  8632. },
  8633. enumerable: true,
  8634. configurable: true
  8635. });
  8636. _StencilState.prototype.reset = function () {
  8637. this._stencilTest = false;
  8638. this._stencilMask = 0xFF;
  8639. this._stencilFunc = BABYLON.Engine.ALWAYS;
  8640. this._stencilFuncRef = 1;
  8641. this._stencilFuncMask = 0xFF;
  8642. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  8643. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  8644. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  8645. this._isStencilTestDirty = true;
  8646. this._isStencilMaskDirty = true;
  8647. this._isStencilFuncDirty = true;
  8648. this._isStencilOpDirty = true;
  8649. };
  8650. _StencilState.prototype.apply = function (gl) {
  8651. if (!this.isDirty) {
  8652. return;
  8653. }
  8654. // Stencil test
  8655. if (this._isStencilTestDirty) {
  8656. if (this.stencilTest) {
  8657. gl.enable(gl.STENCIL_TEST);
  8658. }
  8659. else {
  8660. gl.disable(gl.STENCIL_TEST);
  8661. }
  8662. this._isStencilTestDirty = false;
  8663. }
  8664. // Stencil mask
  8665. if (this._isStencilMaskDirty) {
  8666. gl.stencilMask(this.stencilMask);
  8667. this._isStencilMaskDirty = false;
  8668. }
  8669. // Stencil func
  8670. if (this._isStencilFuncDirty) {
  8671. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  8672. this._isStencilFuncDirty = false;
  8673. }
  8674. // Stencil op
  8675. if (this._isStencilOpDirty) {
  8676. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  8677. this._isStencilOpDirty = false;
  8678. }
  8679. };
  8680. return _StencilState;
  8681. }());
  8682. BABYLON._StencilState = _StencilState;
  8683. })(BABYLON || (BABYLON = {}));
  8684. //# sourceMappingURL=babylon.stencilState.js.map
  8685. var BABYLON;
  8686. (function (BABYLON) {
  8687. var compileShader = function (gl, source, type, defines, shaderVersion) {
  8688. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  8689. };
  8690. var compileRawShader = function (gl, source, type) {
  8691. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  8692. gl.shaderSource(shader, source);
  8693. gl.compileShader(shader);
  8694. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8695. var log = gl.getShaderInfoLog(shader);
  8696. if (log) {
  8697. throw new Error(log);
  8698. }
  8699. }
  8700. if (!shader) {
  8701. throw new Error("Something went wrong while compile the shader.");
  8702. }
  8703. return shader;
  8704. };
  8705. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  8706. var magFilter = gl.NEAREST;
  8707. var minFilter = gl.NEAREST;
  8708. switch (samplingMode) {
  8709. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  8710. magFilter = gl.LINEAR;
  8711. if (generateMipMaps) {
  8712. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8713. }
  8714. else {
  8715. minFilter = gl.LINEAR;
  8716. }
  8717. break;
  8718. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  8719. magFilter = gl.LINEAR;
  8720. if (generateMipMaps) {
  8721. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8722. }
  8723. else {
  8724. minFilter = gl.LINEAR;
  8725. }
  8726. break;
  8727. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  8728. magFilter = gl.NEAREST;
  8729. if (generateMipMaps) {
  8730. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8731. }
  8732. else {
  8733. minFilter = gl.NEAREST;
  8734. }
  8735. break;
  8736. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  8737. magFilter = gl.NEAREST;
  8738. if (generateMipMaps) {
  8739. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8740. }
  8741. else {
  8742. minFilter = gl.NEAREST;
  8743. }
  8744. break;
  8745. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  8746. magFilter = gl.NEAREST;
  8747. if (generateMipMaps) {
  8748. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8749. }
  8750. else {
  8751. minFilter = gl.LINEAR;
  8752. }
  8753. break;
  8754. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  8755. magFilter = gl.NEAREST;
  8756. if (generateMipMaps) {
  8757. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8758. }
  8759. else {
  8760. minFilter = gl.LINEAR;
  8761. }
  8762. break;
  8763. case BABYLON.Texture.NEAREST_LINEAR:
  8764. magFilter = gl.NEAREST;
  8765. minFilter = gl.LINEAR;
  8766. break;
  8767. case BABYLON.Texture.NEAREST_NEAREST:
  8768. magFilter = gl.NEAREST;
  8769. minFilter = gl.NEAREST;
  8770. break;
  8771. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  8772. magFilter = gl.LINEAR;
  8773. if (generateMipMaps) {
  8774. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8775. }
  8776. else {
  8777. minFilter = gl.NEAREST;
  8778. }
  8779. break;
  8780. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  8781. magFilter = gl.LINEAR;
  8782. if (generateMipMaps) {
  8783. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8784. }
  8785. else {
  8786. minFilter = gl.NEAREST;
  8787. }
  8788. break;
  8789. case BABYLON.Texture.LINEAR_LINEAR:
  8790. magFilter = gl.LINEAR;
  8791. minFilter = gl.LINEAR;
  8792. break;
  8793. case BABYLON.Texture.LINEAR_NEAREST:
  8794. magFilter = gl.LINEAR;
  8795. minFilter = gl.NEAREST;
  8796. break;
  8797. }
  8798. return {
  8799. min: minFilter,
  8800. mag: magFilter
  8801. };
  8802. };
  8803. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  8804. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  8805. var img;
  8806. var onload = function () {
  8807. loadedImages[index] = img;
  8808. loadedImages._internalCount++;
  8809. if (scene) {
  8810. scene._removePendingData(img);
  8811. }
  8812. if (loadedImages._internalCount === 6) {
  8813. onfinish(loadedImages);
  8814. }
  8815. };
  8816. var onerror = function (message, exception) {
  8817. if (scene) {
  8818. scene._removePendingData(img);
  8819. }
  8820. if (onErrorCallBack) {
  8821. onErrorCallBack(message, exception);
  8822. }
  8823. };
  8824. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  8825. if (scene) {
  8826. scene._addPendingData(img);
  8827. }
  8828. };
  8829. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  8830. if (onError === void 0) { onError = null; }
  8831. var loadedImages = [];
  8832. loadedImages._internalCount = 0;
  8833. for (var index = 0; index < 6; index++) {
  8834. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  8835. }
  8836. };
  8837. var BufferPointer = /** @class */ (function () {
  8838. function BufferPointer() {
  8839. }
  8840. return BufferPointer;
  8841. }());
  8842. var InstancingAttributeInfo = /** @class */ (function () {
  8843. function InstancingAttributeInfo() {
  8844. }
  8845. return InstancingAttributeInfo;
  8846. }());
  8847. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  8848. /**
  8849. * Define options used to create a render target texture
  8850. */
  8851. var RenderTargetCreationOptions = /** @class */ (function () {
  8852. function RenderTargetCreationOptions() {
  8853. }
  8854. return RenderTargetCreationOptions;
  8855. }());
  8856. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  8857. /**
  8858. * Regroup several parameters relative to the browser in use
  8859. */
  8860. var EngineCapabilities = /** @class */ (function () {
  8861. function EngineCapabilities() {
  8862. }
  8863. return EngineCapabilities;
  8864. }());
  8865. BABYLON.EngineCapabilities = EngineCapabilities;
  8866. /**
  8867. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  8868. */
  8869. var Engine = /** @class */ (function () {
  8870. /**
  8871. * @constructor
  8872. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  8873. * @param antialias defines enable antialiasing (default: false)
  8874. * @param options defines further options to be sent to the getContext() function
  8875. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  8876. */
  8877. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  8878. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  8879. var _this = this;
  8880. // Public members
  8881. this.forcePOTTextures = false;
  8882. this.isFullscreen = false;
  8883. this.isPointerLock = false;
  8884. this.cullBackFaces = true;
  8885. this.renderEvenInBackground = true;
  8886. this.preventCacheWipeBetweenFrames = false;
  8887. // To enable/disable IDB support and avoid XHR on .manifest
  8888. this.enableOfflineSupport = false;
  8889. this.scenes = new Array();
  8890. this.postProcesses = new Array();
  8891. // Observables
  8892. /**
  8893. * Observable event triggered each time the rendering canvas is resized
  8894. */
  8895. this.onResizeObservable = new BABYLON.Observable();
  8896. /**
  8897. * Observable event triggered each time the canvas loses focus
  8898. */
  8899. this.onCanvasBlurObservable = new BABYLON.Observable();
  8900. /**
  8901. * Observable event triggered each time the canvas gains focus
  8902. */
  8903. this.onCanvasFocusObservable = new BABYLON.Observable();
  8904. /**
  8905. * Observable event triggered each time the canvas receives pointerout event
  8906. */
  8907. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  8908. /**
  8909. * Observable event triggered before each texture is initialized
  8910. */
  8911. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8912. //WebVR
  8913. this._vrDisplay = undefined;
  8914. this._vrSupported = false;
  8915. this._vrExclusivePointerMode = false;
  8916. // Uniform buffers list
  8917. this.disableUniformBuffers = false;
  8918. this._uniformBuffers = new Array();
  8919. // Observables
  8920. /**
  8921. * Observable raised when the engine begins a new frame
  8922. */
  8923. this.onBeginFrameObservable = new BABYLON.Observable();
  8924. /**
  8925. * Observable raised when the engine ends the current frame
  8926. */
  8927. this.onEndFrameObservable = new BABYLON.Observable();
  8928. /**
  8929. * Observable raised when the engine is about to compile a shader
  8930. */
  8931. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8932. /**
  8933. * Observable raised when the engine has jsut compiled a shader
  8934. */
  8935. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8936. this._windowIsBackground = false;
  8937. this._webGLVersion = 1.0;
  8938. this._badOS = false;
  8939. this._badDesktopOS = false;
  8940. /**
  8941. * Gets or sets a value indicating if we want to disable texture binding optmization.
  8942. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  8943. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  8944. */
  8945. this.disableTextureBindingOptimization = false;
  8946. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8947. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8948. this.onVRRequestPresentStart = new BABYLON.Observable();
  8949. this._colorWrite = true;
  8950. this._drawCalls = new BABYLON.PerfCounter();
  8951. this._textureCollisions = new BABYLON.PerfCounter();
  8952. this._renderingQueueLaunched = false;
  8953. this._activeRenderLoops = new Array();
  8954. // Deterministic lockstepMaxSteps
  8955. this._deterministicLockstep = false;
  8956. this._lockstepMaxSteps = 4;
  8957. // Lost context
  8958. this.onContextLostObservable = new BABYLON.Observable();
  8959. this.onContextRestoredObservable = new BABYLON.Observable();
  8960. this._contextWasLost = false;
  8961. this._doNotHandleContextLost = false;
  8962. // FPS
  8963. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8964. this._fps = 60;
  8965. this._deltaTime = 0;
  8966. /**
  8967. * Turn this value on if you want to pause FPS computation when in background
  8968. */
  8969. this.disablePerformanceMonitorInBackground = false;
  8970. // States
  8971. this._depthCullingState = new BABYLON._DepthCullingState();
  8972. this._stencilState = new BABYLON._StencilState();
  8973. this._alphaState = new BABYLON._AlphaState();
  8974. this._alphaMode = Engine.ALPHA_DISABLE;
  8975. // Cache
  8976. this._internalTexturesCache = new Array();
  8977. this._activeChannel = 0;
  8978. this._currentTextureChannel = -1;
  8979. this._boundTexturesCache = {};
  8980. this._boundTexturesStack = new Array();
  8981. this._compiledEffects = {};
  8982. this._vertexAttribArraysEnabled = [];
  8983. this._uintIndicesCurrentlySet = false;
  8984. this._currentBoundBuffer = new Array();
  8985. this._currentBufferPointers = new Array();
  8986. this._currentInstanceLocations = new Array();
  8987. this._currentInstanceBuffers = new Array();
  8988. this._vaoRecordInProgress = false;
  8989. this._mustWipeVertexAttributes = false;
  8990. this._nextFreeTextureSlots = new Array();
  8991. this._maxSimultaneousTextures = 0;
  8992. this._activeRequests = new Array();
  8993. // Hardware supported Compressed Textures
  8994. this._texturesSupported = new Array();
  8995. this._onVRFullScreenTriggered = function () {
  8996. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8997. //get the old size before we change
  8998. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8999. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  9000. //get the width and height, change the render size
  9001. var leftEye = _this._vrDisplay.getEyeParameters('left');
  9002. _this.setHardwareScalingLevel(1);
  9003. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  9004. }
  9005. else {
  9006. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  9007. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  9008. }
  9009. };
  9010. this._boundUniforms = {};
  9011. var canvas = null;
  9012. Engine.Instances.push(this);
  9013. if (!canvasOrContext) {
  9014. return;
  9015. }
  9016. options = options || {};
  9017. if (canvasOrContext.getContext) {
  9018. canvas = canvasOrContext;
  9019. this._renderingCanvas = canvas;
  9020. if (antialias != null) {
  9021. options.antialias = antialias;
  9022. }
  9023. if (options.deterministicLockstep === undefined) {
  9024. options.deterministicLockstep = false;
  9025. }
  9026. if (options.lockstepMaxSteps === undefined) {
  9027. options.lockstepMaxSteps = 4;
  9028. }
  9029. if (options.preserveDrawingBuffer === undefined) {
  9030. options.preserveDrawingBuffer = false;
  9031. }
  9032. if (options.audioEngine === undefined) {
  9033. options.audioEngine = true;
  9034. }
  9035. if (options.stencil === undefined) {
  9036. options.stencil = true;
  9037. }
  9038. this._deterministicLockstep = options.deterministicLockstep;
  9039. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9040. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9041. // Exceptions
  9042. if (navigator && navigator.userAgent) {
  9043. var ua = navigator.userAgent;
  9044. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9045. var exception = _a[_i];
  9046. var key = exception.key;
  9047. var targets = exception.targets;
  9048. if (ua.indexOf(key) > -1) {
  9049. if (exception.capture && exception.captureConstraint) {
  9050. var capture = exception.capture;
  9051. var constraint = exception.captureConstraint;
  9052. var regex = new RegExp(capture);
  9053. var matches = regex.exec(ua);
  9054. if (matches && matches.length > 0) {
  9055. var capturedValue = parseInt(matches[matches.length - 1]);
  9056. if (capturedValue >= constraint) {
  9057. continue;
  9058. }
  9059. }
  9060. }
  9061. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9062. var target = targets_1[_b];
  9063. switch (target) {
  9064. case "uniformBuffer":
  9065. this.disableUniformBuffers = true;
  9066. break;
  9067. case "textureBindingOptimization":
  9068. this.disableTextureBindingOptimization = true;
  9069. break;
  9070. }
  9071. }
  9072. break;
  9073. }
  9074. }
  9075. }
  9076. // GL
  9077. if (!options.disableWebGL2Support) {
  9078. try {
  9079. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9080. if (this._gl) {
  9081. this._webGLVersion = 2.0;
  9082. }
  9083. }
  9084. catch (e) {
  9085. // Do nothing
  9086. }
  9087. }
  9088. if (!this._gl) {
  9089. if (!canvas) {
  9090. throw new Error("The provided canvas is null or undefined.");
  9091. }
  9092. try {
  9093. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9094. }
  9095. catch (e) {
  9096. throw new Error("WebGL not supported");
  9097. }
  9098. }
  9099. if (!this._gl) {
  9100. throw new Error("WebGL not supported");
  9101. }
  9102. this._onCanvasFocus = function () {
  9103. _this.onCanvasFocusObservable.notifyObservers(_this);
  9104. };
  9105. this._onCanvasBlur = function () {
  9106. _this.onCanvasBlurObservable.notifyObservers(_this);
  9107. };
  9108. canvas.addEventListener("focus", this._onCanvasFocus);
  9109. canvas.addEventListener("blur", this._onCanvasBlur);
  9110. this._onBlur = function () {
  9111. if (_this.disablePerformanceMonitorInBackground) {
  9112. _this._performanceMonitor.disable();
  9113. }
  9114. _this._windowIsBackground = true;
  9115. };
  9116. this._onFocus = function () {
  9117. if (_this.disablePerformanceMonitorInBackground) {
  9118. _this._performanceMonitor.enable();
  9119. }
  9120. _this._windowIsBackground = false;
  9121. };
  9122. this._onCanvasPointerOut = function () {
  9123. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9124. };
  9125. window.addEventListener("blur", this._onBlur);
  9126. window.addEventListener("focus", this._onFocus);
  9127. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9128. // Context lost
  9129. if (!this._doNotHandleContextLost) {
  9130. this._onContextLost = function (evt) {
  9131. evt.preventDefault();
  9132. _this._contextWasLost = true;
  9133. BABYLON.Tools.Warn("WebGL context lost.");
  9134. _this.onContextLostObservable.notifyObservers(_this);
  9135. };
  9136. this._onContextRestored = function (evt) {
  9137. // Adding a timeout to avoid race condition at browser level
  9138. setTimeout(function () {
  9139. // Rebuild gl context
  9140. _this._initGLContext();
  9141. // Rebuild effects
  9142. _this._rebuildEffects();
  9143. // Rebuild textures
  9144. _this._rebuildInternalTextures();
  9145. // Rebuild buffers
  9146. _this._rebuildBuffers();
  9147. // Cache
  9148. _this.wipeCaches(true);
  9149. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9150. _this.onContextRestoredObservable.notifyObservers(_this);
  9151. _this._contextWasLost = false;
  9152. }, 0);
  9153. };
  9154. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9155. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9156. }
  9157. }
  9158. else {
  9159. this._gl = canvasOrContext;
  9160. this._renderingCanvas = this._gl.canvas;
  9161. if (this._gl.renderbufferStorageMultisample) {
  9162. this._webGLVersion = 2.0;
  9163. }
  9164. options.stencil = this._gl.getContextAttributes().stencil;
  9165. }
  9166. // Viewport
  9167. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9168. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9169. this.resize();
  9170. this._isStencilEnable = options.stencil ? true : false;
  9171. this._initGLContext();
  9172. if (canvas) {
  9173. // Fullscreen
  9174. this._onFullscreenChange = function () {
  9175. if (document.fullscreen !== undefined) {
  9176. _this.isFullscreen = document.fullscreen;
  9177. }
  9178. else if (document.mozFullScreen !== undefined) {
  9179. _this.isFullscreen = document.mozFullScreen;
  9180. }
  9181. else if (document.webkitIsFullScreen !== undefined) {
  9182. _this.isFullscreen = document.webkitIsFullScreen;
  9183. }
  9184. else if (document.msIsFullScreen !== undefined) {
  9185. _this.isFullscreen = document.msIsFullScreen;
  9186. }
  9187. // Pointer lock
  9188. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9189. canvas.requestPointerLock = canvas.requestPointerLock ||
  9190. canvas.msRequestPointerLock ||
  9191. canvas.mozRequestPointerLock ||
  9192. canvas.webkitRequestPointerLock;
  9193. if (canvas.requestPointerLock) {
  9194. canvas.requestPointerLock();
  9195. }
  9196. }
  9197. };
  9198. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9199. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9200. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9201. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9202. // Pointer lock
  9203. this._onPointerLockChange = function () {
  9204. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9205. document.webkitPointerLockElement === canvas ||
  9206. document.msPointerLockElement === canvas ||
  9207. document.pointerLockElement === canvas);
  9208. };
  9209. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9210. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9211. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9212. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9213. this._onVRDisplayPointerRestricted = function () {
  9214. if (canvas) {
  9215. canvas.requestPointerLock();
  9216. }
  9217. };
  9218. this._onVRDisplayPointerUnrestricted = function () {
  9219. document.exitPointerLock();
  9220. };
  9221. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9222. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9223. }
  9224. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9225. Engine.audioEngine = new BABYLON.AudioEngine();
  9226. }
  9227. // Prepare buffer pointers
  9228. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9229. this._currentBufferPointers[i] = new BufferPointer();
  9230. }
  9231. // Load WebVR Devices
  9232. if (options.autoEnableWebVR) {
  9233. this.initWebVR();
  9234. }
  9235. // Detect if we are running on a faulty buggy OS.
  9236. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9237. // Detect if we are running on a faulty buggy desktop OS.
  9238. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9239. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9240. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9241. }
  9242. Object.defineProperty(Engine, "LastCreatedEngine", {
  9243. get: function () {
  9244. if (Engine.Instances.length === 0) {
  9245. return null;
  9246. }
  9247. return Engine.Instances[Engine.Instances.length - 1];
  9248. },
  9249. enumerable: true,
  9250. configurable: true
  9251. });
  9252. Object.defineProperty(Engine, "LastCreatedScene", {
  9253. get: function () {
  9254. var lastCreatedEngine = Engine.LastCreatedEngine;
  9255. if (!lastCreatedEngine) {
  9256. return null;
  9257. }
  9258. if (lastCreatedEngine.scenes.length === 0) {
  9259. return null;
  9260. }
  9261. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9262. },
  9263. enumerable: true,
  9264. configurable: true
  9265. });
  9266. /**
  9267. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9268. */
  9269. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9270. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9271. var engine = Engine.Instances[engineIndex];
  9272. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9273. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9274. }
  9275. }
  9276. };
  9277. Object.defineProperty(Engine, "NEVER", {
  9278. get: function () {
  9279. return Engine._NEVER;
  9280. },
  9281. enumerable: true,
  9282. configurable: true
  9283. });
  9284. Object.defineProperty(Engine, "ALWAYS", {
  9285. get: function () {
  9286. return Engine._ALWAYS;
  9287. },
  9288. enumerable: true,
  9289. configurable: true
  9290. });
  9291. Object.defineProperty(Engine, "LESS", {
  9292. get: function () {
  9293. return Engine._LESS;
  9294. },
  9295. enumerable: true,
  9296. configurable: true
  9297. });
  9298. Object.defineProperty(Engine, "EQUAL", {
  9299. get: function () {
  9300. return Engine._EQUAL;
  9301. },
  9302. enumerable: true,
  9303. configurable: true
  9304. });
  9305. Object.defineProperty(Engine, "LEQUAL", {
  9306. get: function () {
  9307. return Engine._LEQUAL;
  9308. },
  9309. enumerable: true,
  9310. configurable: true
  9311. });
  9312. Object.defineProperty(Engine, "GREATER", {
  9313. get: function () {
  9314. return Engine._GREATER;
  9315. },
  9316. enumerable: true,
  9317. configurable: true
  9318. });
  9319. Object.defineProperty(Engine, "GEQUAL", {
  9320. get: function () {
  9321. return Engine._GEQUAL;
  9322. },
  9323. enumerable: true,
  9324. configurable: true
  9325. });
  9326. Object.defineProperty(Engine, "NOTEQUAL", {
  9327. get: function () {
  9328. return Engine._NOTEQUAL;
  9329. },
  9330. enumerable: true,
  9331. configurable: true
  9332. });
  9333. Object.defineProperty(Engine, "KEEP", {
  9334. get: function () {
  9335. return Engine._KEEP;
  9336. },
  9337. enumerable: true,
  9338. configurable: true
  9339. });
  9340. Object.defineProperty(Engine, "REPLACE", {
  9341. get: function () {
  9342. return Engine._REPLACE;
  9343. },
  9344. enumerable: true,
  9345. configurable: true
  9346. });
  9347. Object.defineProperty(Engine, "INCR", {
  9348. get: function () {
  9349. return Engine._INCR;
  9350. },
  9351. enumerable: true,
  9352. configurable: true
  9353. });
  9354. Object.defineProperty(Engine, "DECR", {
  9355. get: function () {
  9356. return Engine._DECR;
  9357. },
  9358. enumerable: true,
  9359. configurable: true
  9360. });
  9361. Object.defineProperty(Engine, "INVERT", {
  9362. get: function () {
  9363. return Engine._INVERT;
  9364. },
  9365. enumerable: true,
  9366. configurable: true
  9367. });
  9368. Object.defineProperty(Engine, "INCR_WRAP", {
  9369. get: function () {
  9370. return Engine._INCR_WRAP;
  9371. },
  9372. enumerable: true,
  9373. configurable: true
  9374. });
  9375. Object.defineProperty(Engine, "DECR_WRAP", {
  9376. get: function () {
  9377. return Engine._DECR_WRAP;
  9378. },
  9379. enumerable: true,
  9380. configurable: true
  9381. });
  9382. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9383. get: function () {
  9384. return Engine._ALPHA_DISABLE;
  9385. },
  9386. enumerable: true,
  9387. configurable: true
  9388. });
  9389. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9390. get: function () {
  9391. return Engine._ALPHA_ONEONE;
  9392. },
  9393. enumerable: true,
  9394. configurable: true
  9395. });
  9396. Object.defineProperty(Engine, "ALPHA_ADD", {
  9397. get: function () {
  9398. return Engine._ALPHA_ADD;
  9399. },
  9400. enumerable: true,
  9401. configurable: true
  9402. });
  9403. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9404. get: function () {
  9405. return Engine._ALPHA_COMBINE;
  9406. },
  9407. enumerable: true,
  9408. configurable: true
  9409. });
  9410. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9411. get: function () {
  9412. return Engine._ALPHA_SUBTRACT;
  9413. },
  9414. enumerable: true,
  9415. configurable: true
  9416. });
  9417. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9418. get: function () {
  9419. return Engine._ALPHA_MULTIPLY;
  9420. },
  9421. enumerable: true,
  9422. configurable: true
  9423. });
  9424. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9425. get: function () {
  9426. return Engine._ALPHA_MAXIMIZED;
  9427. },
  9428. enumerable: true,
  9429. configurable: true
  9430. });
  9431. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9432. get: function () {
  9433. return Engine._ALPHA_PREMULTIPLIED;
  9434. },
  9435. enumerable: true,
  9436. configurable: true
  9437. });
  9438. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9439. get: function () {
  9440. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9441. },
  9442. enumerable: true,
  9443. configurable: true
  9444. });
  9445. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9446. get: function () {
  9447. return Engine._ALPHA_INTERPOLATE;
  9448. },
  9449. enumerable: true,
  9450. configurable: true
  9451. });
  9452. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9453. get: function () {
  9454. return Engine._ALPHA_SCREENMODE;
  9455. },
  9456. enumerable: true,
  9457. configurable: true
  9458. });
  9459. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9460. get: function () {
  9461. return Engine._DELAYLOADSTATE_NONE;
  9462. },
  9463. enumerable: true,
  9464. configurable: true
  9465. });
  9466. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9467. get: function () {
  9468. return Engine._DELAYLOADSTATE_LOADED;
  9469. },
  9470. enumerable: true,
  9471. configurable: true
  9472. });
  9473. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  9474. get: function () {
  9475. return Engine._DELAYLOADSTATE_LOADING;
  9476. },
  9477. enumerable: true,
  9478. configurable: true
  9479. });
  9480. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  9481. get: function () {
  9482. return Engine._DELAYLOADSTATE_NOTLOADED;
  9483. },
  9484. enumerable: true,
  9485. configurable: true
  9486. });
  9487. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  9488. get: function () {
  9489. return Engine._TEXTUREFORMAT_ALPHA;
  9490. },
  9491. enumerable: true,
  9492. configurable: true
  9493. });
  9494. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  9495. get: function () {
  9496. return Engine._TEXTUREFORMAT_LUMINANCE;
  9497. },
  9498. enumerable: true,
  9499. configurable: true
  9500. });
  9501. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  9502. get: function () {
  9503. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  9504. },
  9505. enumerable: true,
  9506. configurable: true
  9507. });
  9508. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  9509. get: function () {
  9510. return Engine._TEXTUREFORMAT_RGB;
  9511. },
  9512. enumerable: true,
  9513. configurable: true
  9514. });
  9515. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  9516. get: function () {
  9517. return Engine._TEXTUREFORMAT_RGBA;
  9518. },
  9519. enumerable: true,
  9520. configurable: true
  9521. });
  9522. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  9523. get: function () {
  9524. return Engine._TEXTURETYPE_UNSIGNED_INT;
  9525. },
  9526. enumerable: true,
  9527. configurable: true
  9528. });
  9529. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  9530. get: function () {
  9531. return Engine._TEXTURETYPE_FLOAT;
  9532. },
  9533. enumerable: true,
  9534. configurable: true
  9535. });
  9536. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  9537. get: function () {
  9538. return Engine._TEXTURETYPE_HALF_FLOAT;
  9539. },
  9540. enumerable: true,
  9541. configurable: true
  9542. });
  9543. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  9544. get: function () {
  9545. return Engine._SCALEMODE_FLOOR;
  9546. },
  9547. enumerable: true,
  9548. configurable: true
  9549. });
  9550. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  9551. get: function () {
  9552. return Engine._SCALEMODE_NEAREST;
  9553. },
  9554. enumerable: true,
  9555. configurable: true
  9556. });
  9557. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  9558. get: function () {
  9559. return Engine._SCALEMODE_CEILING;
  9560. },
  9561. enumerable: true,
  9562. configurable: true
  9563. });
  9564. Object.defineProperty(Engine, "Version", {
  9565. get: function () {
  9566. return "3.2.0-alpha4";
  9567. },
  9568. enumerable: true,
  9569. configurable: true
  9570. });
  9571. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  9572. get: function () {
  9573. return this._vrExclusivePointerMode;
  9574. },
  9575. enumerable: true,
  9576. configurable: true
  9577. });
  9578. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  9579. get: function () {
  9580. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  9581. },
  9582. enumerable: true,
  9583. configurable: true
  9584. });
  9585. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  9586. get: function () {
  9587. return this._webGLVersion < 2 || this.forcePOTTextures;
  9588. },
  9589. enumerable: true,
  9590. configurable: true
  9591. });
  9592. Object.defineProperty(Engine.prototype, "badOS", {
  9593. get: function () {
  9594. return this._badOS;
  9595. },
  9596. enumerable: true,
  9597. configurable: true
  9598. });
  9599. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  9600. get: function () {
  9601. return this._badDesktopOS;
  9602. },
  9603. enumerable: true,
  9604. configurable: true
  9605. });
  9606. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  9607. get: function () {
  9608. return this._performanceMonitor;
  9609. },
  9610. enumerable: true,
  9611. configurable: true
  9612. });
  9613. Object.defineProperty(Engine.prototype, "texturesSupported", {
  9614. get: function () {
  9615. return this._texturesSupported;
  9616. },
  9617. enumerable: true,
  9618. configurable: true
  9619. });
  9620. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  9621. get: function () {
  9622. return this._textureFormatInUse;
  9623. },
  9624. enumerable: true,
  9625. configurable: true
  9626. });
  9627. Object.defineProperty(Engine.prototype, "currentViewport", {
  9628. get: function () {
  9629. return this._cachedViewport;
  9630. },
  9631. enumerable: true,
  9632. configurable: true
  9633. });
  9634. Object.defineProperty(Engine.prototype, "emptyTexture", {
  9635. // Empty texture
  9636. get: function () {
  9637. if (!this._emptyTexture) {
  9638. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9639. }
  9640. return this._emptyTexture;
  9641. },
  9642. enumerable: true,
  9643. configurable: true
  9644. });
  9645. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  9646. get: function () {
  9647. if (!this._emptyTexture3D) {
  9648. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9649. }
  9650. return this._emptyTexture3D;
  9651. },
  9652. enumerable: true,
  9653. configurable: true
  9654. });
  9655. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  9656. get: function () {
  9657. if (!this._emptyCubeTexture) {
  9658. var faceData = new Uint8Array(4);
  9659. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  9660. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9661. }
  9662. return this._emptyCubeTexture;
  9663. },
  9664. enumerable: true,
  9665. configurable: true
  9666. });
  9667. Engine.prototype._rebuildInternalTextures = function () {
  9668. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  9669. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  9670. var internalTexture = currentState_1[_i];
  9671. internalTexture._rebuild();
  9672. }
  9673. };
  9674. Engine.prototype._rebuildEffects = function () {
  9675. for (var key in this._compiledEffects) {
  9676. var effect = this._compiledEffects[key];
  9677. effect._prepareEffect();
  9678. }
  9679. BABYLON.Effect.ResetCache();
  9680. };
  9681. Engine.prototype._rebuildBuffers = function () {
  9682. // Index / Vertex
  9683. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  9684. var scene = _a[_i];
  9685. scene.resetCachedMaterial();
  9686. scene._rebuildGeometries();
  9687. scene._rebuildTextures();
  9688. }
  9689. // Uniforms
  9690. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  9691. var uniformBuffer = _c[_b];
  9692. uniformBuffer._rebuild();
  9693. }
  9694. };
  9695. Engine.prototype._initGLContext = function () {
  9696. // Caps
  9697. this._caps = new EngineCapabilities();
  9698. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  9699. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  9700. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9701. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  9702. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9703. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  9704. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  9705. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  9706. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9707. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  9708. // Infos
  9709. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  9710. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  9711. if (rendererInfo != null) {
  9712. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  9713. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  9714. }
  9715. if (!this._glVendor) {
  9716. this._glVendor = "Unknown vendor";
  9717. }
  9718. if (!this._glRenderer) {
  9719. this._glRenderer = "Unknown renderer";
  9720. }
  9721. // Constants
  9722. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9723. if (this._gl.RGBA16F !== 0x881A) {
  9724. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9725. }
  9726. if (this._gl.RGBA32F !== 0x8814) {
  9727. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9728. }
  9729. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  9730. this._gl.DEPTH24_STENCIL8 = 35056;
  9731. }
  9732. // Extensions
  9733. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  9734. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  9735. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9736. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9737. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  9738. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  9739. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  9740. 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');
  9741. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  9742. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  9743. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  9744. this._caps.highPrecisionShaderSupported = true;
  9745. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  9746. if (this._caps.timerQuery) {
  9747. if (this._webGLVersion === 1) {
  9748. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  9749. }
  9750. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  9751. }
  9752. // Checks if some of the format renders first to allow the use of webgl inspector.
  9753. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  9754. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  9755. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  9756. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  9757. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  9758. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  9759. if (this._webGLVersion > 1) {
  9760. this._gl.HALF_FLOAT_OES = 0x140B;
  9761. }
  9762. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  9763. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  9764. // Draw buffers
  9765. if (this._webGLVersion > 1) {
  9766. this._caps.drawBuffersExtension = true;
  9767. }
  9768. else {
  9769. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  9770. if (drawBuffersExtension !== null) {
  9771. this._caps.drawBuffersExtension = true;
  9772. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  9773. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  9774. for (var i = 0; i < 16; i++) {
  9775. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  9776. }
  9777. }
  9778. else {
  9779. this._caps.drawBuffersExtension = false;
  9780. }
  9781. }
  9782. // Depth Texture
  9783. if (this._webGLVersion > 1) {
  9784. this._caps.depthTextureExtension = true;
  9785. }
  9786. else {
  9787. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  9788. if (depthTextureExtension != null) {
  9789. this._caps.depthTextureExtension = true;
  9790. }
  9791. }
  9792. // Vertex array object
  9793. if (this._webGLVersion > 1) {
  9794. this._caps.vertexArrayObject = true;
  9795. }
  9796. else {
  9797. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  9798. if (vertexArrayObjectExtension != null) {
  9799. this._caps.vertexArrayObject = true;
  9800. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  9801. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  9802. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  9803. }
  9804. else {
  9805. this._caps.vertexArrayObject = false;
  9806. }
  9807. }
  9808. // Instances count
  9809. if (this._webGLVersion > 1) {
  9810. this._caps.instancedArrays = true;
  9811. }
  9812. else {
  9813. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  9814. if (instanceExtension != null) {
  9815. this._caps.instancedArrays = true;
  9816. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  9817. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  9818. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  9819. }
  9820. else {
  9821. this._caps.instancedArrays = false;
  9822. }
  9823. }
  9824. // Intelligently add supported compressed formats in order to check for.
  9825. // Check for ASTC support first as it is most powerful and to be very cross platform.
  9826. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  9827. // Likely no hardware which supports both PVR & DXT, so order matters little.
  9828. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  9829. if (this._caps.astc)
  9830. this.texturesSupported.push('-astc.ktx');
  9831. if (this._caps.s3tc)
  9832. this.texturesSupported.push('-dxt.ktx');
  9833. if (this._caps.pvrtc)
  9834. this.texturesSupported.push('-pvrtc.ktx');
  9835. if (this._caps.etc2)
  9836. this.texturesSupported.push('-etc2.ktx');
  9837. if (this._caps.etc1)
  9838. this.texturesSupported.push('-etc1.ktx');
  9839. if (this._gl.getShaderPrecisionFormat) {
  9840. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  9841. if (highp) {
  9842. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  9843. }
  9844. }
  9845. // Depth buffer
  9846. this.setDepthBuffer(true);
  9847. this.setDepthFunctionToLessOrEqual();
  9848. this.setDepthWrite(true);
  9849. // Texture maps
  9850. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  9851. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  9852. this._nextFreeTextureSlots.push(slot);
  9853. }
  9854. };
  9855. Object.defineProperty(Engine.prototype, "webGLVersion", {
  9856. get: function () {
  9857. return this._webGLVersion;
  9858. },
  9859. enumerable: true,
  9860. configurable: true
  9861. });
  9862. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  9863. /**
  9864. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  9865. */
  9866. get: function () {
  9867. return this._isStencilEnable;
  9868. },
  9869. enumerable: true,
  9870. configurable: true
  9871. });
  9872. Engine.prototype._prepareWorkingCanvas = function () {
  9873. if (this._workingCanvas) {
  9874. return;
  9875. }
  9876. this._workingCanvas = document.createElement("canvas");
  9877. var context = this._workingCanvas.getContext("2d");
  9878. if (context) {
  9879. this._workingContext = context;
  9880. }
  9881. };
  9882. Engine.prototype.resetTextureCache = function () {
  9883. for (var key in this._boundTexturesCache) {
  9884. var boundTexture = this._boundTexturesCache[key];
  9885. if (boundTexture) {
  9886. this._removeDesignatedSlot(boundTexture);
  9887. }
  9888. this._boundTexturesCache[key] = null;
  9889. }
  9890. this._nextFreeTextureSlots = [];
  9891. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  9892. this._nextFreeTextureSlots.push(slot);
  9893. }
  9894. this._currentTextureChannel = -1;
  9895. };
  9896. Engine.prototype.isDeterministicLockStep = function () {
  9897. return this._deterministicLockstep;
  9898. };
  9899. Engine.prototype.getLockstepMaxSteps = function () {
  9900. return this._lockstepMaxSteps;
  9901. };
  9902. Engine.prototype.getGlInfo = function () {
  9903. return {
  9904. vendor: this._glVendor,
  9905. renderer: this._glRenderer,
  9906. version: this._glVersion
  9907. };
  9908. };
  9909. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  9910. if (useScreen === void 0) { useScreen = false; }
  9911. var viewport = camera.viewport;
  9912. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  9913. };
  9914. Engine.prototype.getRenderWidth = function (useScreen) {
  9915. if (useScreen === void 0) { useScreen = false; }
  9916. if (!useScreen && this._currentRenderTarget) {
  9917. return this._currentRenderTarget.width;
  9918. }
  9919. return this._gl.drawingBufferWidth;
  9920. };
  9921. Engine.prototype.getRenderHeight = function (useScreen) {
  9922. if (useScreen === void 0) { useScreen = false; }
  9923. if (!useScreen && this._currentRenderTarget) {
  9924. return this._currentRenderTarget.height;
  9925. }
  9926. return this._gl.drawingBufferHeight;
  9927. };
  9928. Engine.prototype.getRenderingCanvas = function () {
  9929. return this._renderingCanvas;
  9930. };
  9931. Engine.prototype.getRenderingCanvasClientRect = function () {
  9932. if (!this._renderingCanvas) {
  9933. return null;
  9934. }
  9935. return this._renderingCanvas.getBoundingClientRect();
  9936. };
  9937. Engine.prototype.setHardwareScalingLevel = function (level) {
  9938. this._hardwareScalingLevel = level;
  9939. this.resize();
  9940. };
  9941. Engine.prototype.getHardwareScalingLevel = function () {
  9942. return this._hardwareScalingLevel;
  9943. };
  9944. Engine.prototype.getLoadedTexturesCache = function () {
  9945. return this._internalTexturesCache;
  9946. };
  9947. Engine.prototype.getCaps = function () {
  9948. return this._caps;
  9949. };
  9950. Object.defineProperty(Engine.prototype, "drawCalls", {
  9951. /** The number of draw calls submitted last frame */
  9952. get: function () {
  9953. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  9954. return 0;
  9955. },
  9956. enumerable: true,
  9957. configurable: true
  9958. });
  9959. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  9960. get: function () {
  9961. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  9962. return null;
  9963. },
  9964. enumerable: true,
  9965. configurable: true
  9966. });
  9967. Engine.prototype.getDepthFunction = function () {
  9968. return this._depthCullingState.depthFunc;
  9969. };
  9970. Engine.prototype.setDepthFunction = function (depthFunc) {
  9971. this._depthCullingState.depthFunc = depthFunc;
  9972. };
  9973. Engine.prototype.setDepthFunctionToGreater = function () {
  9974. this._depthCullingState.depthFunc = this._gl.GREATER;
  9975. };
  9976. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  9977. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  9978. };
  9979. Engine.prototype.setDepthFunctionToLess = function () {
  9980. this._depthCullingState.depthFunc = this._gl.LESS;
  9981. };
  9982. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  9983. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  9984. };
  9985. Engine.prototype.getStencilBuffer = function () {
  9986. return this._stencilState.stencilTest;
  9987. };
  9988. Engine.prototype.setStencilBuffer = function (enable) {
  9989. this._stencilState.stencilTest = enable;
  9990. };
  9991. Engine.prototype.getStencilMask = function () {
  9992. return this._stencilState.stencilMask;
  9993. };
  9994. Engine.prototype.setStencilMask = function (mask) {
  9995. this._stencilState.stencilMask = mask;
  9996. };
  9997. Engine.prototype.getStencilFunction = function () {
  9998. return this._stencilState.stencilFunc;
  9999. };
  10000. Engine.prototype.getStencilFunctionReference = function () {
  10001. return this._stencilState.stencilFuncRef;
  10002. };
  10003. Engine.prototype.getStencilFunctionMask = function () {
  10004. return this._stencilState.stencilFuncMask;
  10005. };
  10006. Engine.prototype.setStencilFunction = function (stencilFunc) {
  10007. this._stencilState.stencilFunc = stencilFunc;
  10008. };
  10009. Engine.prototype.setStencilFunctionReference = function (reference) {
  10010. this._stencilState.stencilFuncRef = reference;
  10011. };
  10012. Engine.prototype.setStencilFunctionMask = function (mask) {
  10013. this._stencilState.stencilFuncMask = mask;
  10014. };
  10015. Engine.prototype.getStencilOperationFail = function () {
  10016. return this._stencilState.stencilOpStencilFail;
  10017. };
  10018. Engine.prototype.getStencilOperationDepthFail = function () {
  10019. return this._stencilState.stencilOpDepthFail;
  10020. };
  10021. Engine.prototype.getStencilOperationPass = function () {
  10022. return this._stencilState.stencilOpStencilDepthPass;
  10023. };
  10024. Engine.prototype.setStencilOperationFail = function (operation) {
  10025. this._stencilState.stencilOpStencilFail = operation;
  10026. };
  10027. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10028. this._stencilState.stencilOpDepthFail = operation;
  10029. };
  10030. Engine.prototype.setStencilOperationPass = function (operation) {
  10031. this._stencilState.stencilOpStencilDepthPass = operation;
  10032. };
  10033. Engine.prototype.setDitheringState = function (value) {
  10034. if (value) {
  10035. this._gl.enable(this._gl.DITHER);
  10036. }
  10037. else {
  10038. this._gl.disable(this._gl.DITHER);
  10039. }
  10040. };
  10041. Engine.prototype.setRasterizerState = function (value) {
  10042. if (value) {
  10043. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10044. }
  10045. else {
  10046. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10047. }
  10048. };
  10049. /**
  10050. * stop executing a render loop function and remove it from the execution array
  10051. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10052. */
  10053. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10054. if (!renderFunction) {
  10055. this._activeRenderLoops = [];
  10056. return;
  10057. }
  10058. var index = this._activeRenderLoops.indexOf(renderFunction);
  10059. if (index >= 0) {
  10060. this._activeRenderLoops.splice(index, 1);
  10061. }
  10062. };
  10063. Engine.prototype._renderLoop = function () {
  10064. if (!this._contextWasLost) {
  10065. var shouldRender = true;
  10066. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10067. shouldRender = false;
  10068. }
  10069. if (shouldRender) {
  10070. // Start new frame
  10071. this.beginFrame();
  10072. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10073. var renderFunction = this._activeRenderLoops[index];
  10074. renderFunction();
  10075. }
  10076. // Present
  10077. this.endFrame();
  10078. }
  10079. }
  10080. if (this._activeRenderLoops.length > 0) {
  10081. // Register new frame
  10082. var requester = null;
  10083. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10084. requester = this._vrDisplay;
  10085. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10086. }
  10087. else {
  10088. this._renderingQueueLaunched = false;
  10089. }
  10090. };
  10091. /**
  10092. * Register and execute a render loop. The engine can have more than one render function.
  10093. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10094. * @example
  10095. * engine.runRenderLoop(function () {
  10096. * scene.render()
  10097. * })
  10098. */
  10099. Engine.prototype.runRenderLoop = function (renderFunction) {
  10100. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10101. return;
  10102. }
  10103. this._activeRenderLoops.push(renderFunction);
  10104. if (!this._renderingQueueLaunched) {
  10105. this._renderingQueueLaunched = true;
  10106. this._bindedRenderFunction = this._renderLoop.bind(this);
  10107. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10108. }
  10109. };
  10110. /**
  10111. * Toggle full screen mode.
  10112. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10113. * @param {any} options - an options object to be sent to the requestFullscreen function
  10114. */
  10115. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10116. if (this.isFullscreen) {
  10117. BABYLON.Tools.ExitFullscreen();
  10118. }
  10119. else {
  10120. this._pointerLockRequested = requestPointerLock;
  10121. if (this._renderingCanvas) {
  10122. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10123. }
  10124. }
  10125. };
  10126. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10127. if (stencil === void 0) { stencil = false; }
  10128. this.applyStates();
  10129. var mode = 0;
  10130. if (backBuffer && color) {
  10131. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10132. mode |= this._gl.COLOR_BUFFER_BIT;
  10133. }
  10134. if (depth) {
  10135. this._gl.clearDepth(1.0);
  10136. mode |= this._gl.DEPTH_BUFFER_BIT;
  10137. }
  10138. if (stencil) {
  10139. this._gl.clearStencil(0);
  10140. mode |= this._gl.STENCIL_BUFFER_BIT;
  10141. }
  10142. this._gl.clear(mode);
  10143. };
  10144. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10145. var gl = this._gl;
  10146. // Save state
  10147. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10148. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10149. // Change state
  10150. gl.enable(gl.SCISSOR_TEST);
  10151. gl.scissor(x, y, width, height);
  10152. // Clear
  10153. this.clear(clearColor, true, true, true);
  10154. // Restore state
  10155. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10156. if (curScissor === true) {
  10157. gl.enable(gl.SCISSOR_TEST);
  10158. }
  10159. else {
  10160. gl.disable(gl.SCISSOR_TEST);
  10161. }
  10162. };
  10163. /**
  10164. * Set the WebGL's viewport
  10165. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10166. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10167. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10168. */
  10169. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10170. var width = requiredWidth || this.getRenderWidth();
  10171. var height = requiredHeight || this.getRenderHeight();
  10172. var x = viewport.x || 0;
  10173. var y = viewport.y || 0;
  10174. this._cachedViewport = viewport;
  10175. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10176. };
  10177. /**
  10178. * Directly set the WebGL Viewport
  10179. * The x, y, width & height are directly passed to the WebGL call
  10180. * @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.
  10181. */
  10182. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10183. var currentViewport = this._cachedViewport;
  10184. this._cachedViewport = null;
  10185. this._gl.viewport(x, y, width, height);
  10186. return currentViewport;
  10187. };
  10188. Engine.prototype.beginFrame = function () {
  10189. this.onBeginFrameObservable.notifyObservers(this);
  10190. this._measureFps();
  10191. };
  10192. Engine.prototype.endFrame = function () {
  10193. //force a flush in case we are using a bad OS.
  10194. if (this._badOS) {
  10195. this.flushFramebuffer();
  10196. }
  10197. //submit frame to the vr device, if enabled
  10198. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10199. // TODO: We should only submit the frame if we read frameData successfully.
  10200. this._vrDisplay.submitFrame();
  10201. }
  10202. this.onEndFrameObservable.notifyObservers(this);
  10203. };
  10204. /**
  10205. * resize the view according to the canvas' size.
  10206. * @example
  10207. * window.addEventListener("resize", function () {
  10208. * engine.resize();
  10209. * });
  10210. */
  10211. Engine.prototype.resize = function () {
  10212. // We're not resizing the size of the canvas while in VR mode & presenting
  10213. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10214. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10215. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10216. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10217. }
  10218. };
  10219. /**
  10220. * force a specific size of the canvas
  10221. * @param {number} width - the new canvas' width
  10222. * @param {number} height - the new canvas' height
  10223. */
  10224. Engine.prototype.setSize = function (width, height) {
  10225. if (!this._renderingCanvas) {
  10226. return;
  10227. }
  10228. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10229. return;
  10230. }
  10231. this._renderingCanvas.width = width;
  10232. this._renderingCanvas.height = height;
  10233. for (var index = 0; index < this.scenes.length; index++) {
  10234. var scene = this.scenes[index];
  10235. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10236. var cam = scene.cameras[camIndex];
  10237. cam._currentRenderId = 0;
  10238. }
  10239. }
  10240. if (this.onResizeObservable.hasObservers) {
  10241. this.onResizeObservable.notifyObservers(this);
  10242. }
  10243. };
  10244. // WebVR functions
  10245. Engine.prototype.isVRDevicePresent = function () {
  10246. return !!this._vrDisplay;
  10247. };
  10248. Engine.prototype.getVRDevice = function () {
  10249. return this._vrDisplay;
  10250. };
  10251. Engine.prototype.initWebVR = function () {
  10252. var _this = this;
  10253. var notifyObservers = function () {
  10254. var eventArgs = {
  10255. vrDisplay: _this._vrDisplay,
  10256. vrSupported: _this._vrSupported
  10257. };
  10258. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10259. };
  10260. if (!this._onVrDisplayConnect) {
  10261. this._onVrDisplayConnect = function (event) {
  10262. _this._vrDisplay = event.display;
  10263. notifyObservers();
  10264. };
  10265. this._onVrDisplayDisconnect = function () {
  10266. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10267. _this._vrDisplay = undefined;
  10268. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10269. notifyObservers();
  10270. };
  10271. this._onVrDisplayPresentChange = function () {
  10272. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10273. };
  10274. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10275. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10276. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10277. }
  10278. this._getVRDisplays(notifyObservers);
  10279. return this.onVRDisplayChangedObservable;
  10280. };
  10281. Engine.prototype.enableVR = function () {
  10282. var _this = this;
  10283. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10284. var onResolved = function () {
  10285. _this.onVRRequestPresentComplete.notifyObservers(true);
  10286. _this._onVRFullScreenTriggered();
  10287. };
  10288. var onRejected = function () {
  10289. _this.onVRRequestPresentComplete.notifyObservers(false);
  10290. };
  10291. this.onVRRequestPresentStart.notifyObservers(this);
  10292. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10293. }
  10294. };
  10295. Engine.prototype.disableVR = function () {
  10296. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10297. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10298. }
  10299. };
  10300. Engine.prototype._getVRDisplays = function (callback) {
  10301. var _this = this;
  10302. var getWebVRDevices = function (devices) {
  10303. _this._vrSupported = true;
  10304. // note that devices may actually be an empty array. This is fine;
  10305. // we expect this._vrDisplay to be undefined in this case.
  10306. return _this._vrDisplay = devices[0];
  10307. };
  10308. if (navigator.getVRDisplays) {
  10309. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10310. // TODO: System CANNOT support WebVR, despite API presence.
  10311. _this._vrSupported = false;
  10312. callback();
  10313. });
  10314. }
  10315. else {
  10316. // TODO: Browser does not support WebVR
  10317. this._vrDisplay = undefined;
  10318. this._vrSupported = false;
  10319. callback();
  10320. }
  10321. };
  10322. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10323. if (this._currentRenderTarget) {
  10324. this.unBindFramebuffer(this._currentRenderTarget);
  10325. }
  10326. this._currentRenderTarget = texture;
  10327. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10328. var gl = this._gl;
  10329. if (texture.isCube) {
  10330. if (faceIndex === undefined) {
  10331. faceIndex = 0;
  10332. }
  10333. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10334. }
  10335. if (this._cachedViewport && !forceFullscreenViewport) {
  10336. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10337. }
  10338. else {
  10339. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10340. }
  10341. this.wipeCaches();
  10342. };
  10343. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10344. if (this._currentFramebuffer !== framebuffer) {
  10345. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10346. this._currentFramebuffer = framebuffer;
  10347. }
  10348. };
  10349. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10350. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10351. this._currentRenderTarget = null;
  10352. // If MSAA, we need to bitblt back to main texture
  10353. var gl = this._gl;
  10354. if (texture._MSAAFramebuffer) {
  10355. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10356. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10357. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10358. }
  10359. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10360. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10361. gl.generateMipmap(gl.TEXTURE_2D);
  10362. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10363. }
  10364. if (onBeforeUnbind) {
  10365. if (texture._MSAAFramebuffer) {
  10366. // Bind the correct framebuffer
  10367. this.bindUnboundFramebuffer(texture._framebuffer);
  10368. }
  10369. onBeforeUnbind();
  10370. }
  10371. this.bindUnboundFramebuffer(null);
  10372. };
  10373. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10374. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10375. this._currentRenderTarget = null;
  10376. // If MSAA, we need to bitblt back to main texture
  10377. var gl = this._gl;
  10378. if (textures[0]._MSAAFramebuffer) {
  10379. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10380. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10381. var attachments = textures[0]._attachments;
  10382. if (!attachments) {
  10383. attachments = new Array(textures.length);
  10384. textures[0]._attachments = attachments;
  10385. }
  10386. for (var i = 0; i < textures.length; i++) {
  10387. var texture = textures[i];
  10388. for (var j = 0; j < attachments.length; j++) {
  10389. attachments[j] = gl.NONE;
  10390. }
  10391. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10392. gl.readBuffer(attachments[i]);
  10393. gl.drawBuffers(attachments);
  10394. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10395. }
  10396. for (var i = 0; i < attachments.length; i++) {
  10397. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10398. }
  10399. gl.drawBuffers(attachments);
  10400. }
  10401. for (var i = 0; i < textures.length; i++) {
  10402. var texture = textures[i];
  10403. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10404. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10405. gl.generateMipmap(gl.TEXTURE_2D);
  10406. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10407. }
  10408. }
  10409. if (onBeforeUnbind) {
  10410. if (textures[0]._MSAAFramebuffer) {
  10411. // Bind the correct framebuffer
  10412. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10413. }
  10414. onBeforeUnbind();
  10415. }
  10416. this.bindUnboundFramebuffer(null);
  10417. };
  10418. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10419. if (texture.generateMipMaps) {
  10420. var gl = this._gl;
  10421. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10422. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10423. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10424. }
  10425. };
  10426. Engine.prototype.flushFramebuffer = function () {
  10427. this._gl.flush();
  10428. };
  10429. Engine.prototype.restoreDefaultFramebuffer = function () {
  10430. if (this._currentRenderTarget) {
  10431. this.unBindFramebuffer(this._currentRenderTarget);
  10432. }
  10433. else {
  10434. this.bindUnboundFramebuffer(null);
  10435. }
  10436. if (this._cachedViewport) {
  10437. this.setViewport(this._cachedViewport);
  10438. }
  10439. this.wipeCaches();
  10440. };
  10441. // UBOs
  10442. Engine.prototype.createUniformBuffer = function (elements) {
  10443. var ubo = this._gl.createBuffer();
  10444. if (!ubo) {
  10445. throw new Error("Unable to create uniform buffer");
  10446. }
  10447. this.bindUniformBuffer(ubo);
  10448. if (elements instanceof Float32Array) {
  10449. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10450. }
  10451. else {
  10452. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10453. }
  10454. this.bindUniformBuffer(null);
  10455. ubo.references = 1;
  10456. return ubo;
  10457. };
  10458. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10459. var ubo = this._gl.createBuffer();
  10460. if (!ubo) {
  10461. throw new Error("Unable to create dynamic uniform buffer");
  10462. }
  10463. this.bindUniformBuffer(ubo);
  10464. if (elements instanceof Float32Array) {
  10465. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10466. }
  10467. else {
  10468. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10469. }
  10470. this.bindUniformBuffer(null);
  10471. ubo.references = 1;
  10472. return ubo;
  10473. };
  10474. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  10475. this.bindUniformBuffer(uniformBuffer);
  10476. if (offset === undefined) {
  10477. offset = 0;
  10478. }
  10479. if (count === undefined) {
  10480. if (elements instanceof Float32Array) {
  10481. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  10482. }
  10483. else {
  10484. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  10485. }
  10486. }
  10487. else {
  10488. if (elements instanceof Float32Array) {
  10489. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  10490. }
  10491. else {
  10492. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  10493. }
  10494. }
  10495. this.bindUniformBuffer(null);
  10496. };
  10497. // VBOs
  10498. Engine.prototype._resetVertexBufferBinding = function () {
  10499. this.bindArrayBuffer(null);
  10500. this._cachedVertexBuffers = null;
  10501. };
  10502. Engine.prototype.createVertexBuffer = function (vertices) {
  10503. var vbo = this._gl.createBuffer();
  10504. if (!vbo) {
  10505. throw new Error("Unable to create vertex buffer");
  10506. }
  10507. this.bindArrayBuffer(vbo);
  10508. if (vertices instanceof Float32Array) {
  10509. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  10510. }
  10511. else {
  10512. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  10513. }
  10514. this._resetVertexBufferBinding();
  10515. vbo.references = 1;
  10516. return vbo;
  10517. };
  10518. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  10519. var vbo = this._gl.createBuffer();
  10520. if (!vbo) {
  10521. throw new Error("Unable to create dynamic vertex buffer");
  10522. }
  10523. this.bindArrayBuffer(vbo);
  10524. if (vertices instanceof Float32Array) {
  10525. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  10526. }
  10527. else {
  10528. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  10529. }
  10530. this._resetVertexBufferBinding();
  10531. vbo.references = 1;
  10532. return vbo;
  10533. };
  10534. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  10535. if (offset === void 0) { offset = 0; }
  10536. // Force cache update
  10537. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  10538. this.bindIndexBuffer(indexBuffer);
  10539. var arrayBuffer;
  10540. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  10541. arrayBuffer = indices;
  10542. }
  10543. else {
  10544. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10545. }
  10546. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  10547. this._resetIndexBufferBinding();
  10548. };
  10549. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  10550. this.bindArrayBuffer(vertexBuffer);
  10551. if (offset === undefined) {
  10552. offset = 0;
  10553. }
  10554. if (count === undefined) {
  10555. if (vertices instanceof Float32Array) {
  10556. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  10557. }
  10558. else {
  10559. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  10560. }
  10561. }
  10562. else {
  10563. if (vertices instanceof Float32Array) {
  10564. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  10565. }
  10566. else {
  10567. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  10568. }
  10569. }
  10570. this._resetVertexBufferBinding();
  10571. };
  10572. Engine.prototype._resetIndexBufferBinding = function () {
  10573. this.bindIndexBuffer(null);
  10574. this._cachedIndexBuffer = null;
  10575. };
  10576. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  10577. var vbo = this._gl.createBuffer();
  10578. if (!vbo) {
  10579. throw new Error("Unable to create index buffer");
  10580. }
  10581. this.bindIndexBuffer(vbo);
  10582. // Check for 32 bits indices
  10583. var arrayBuffer;
  10584. var need32Bits = false;
  10585. if (indices instanceof Uint16Array) {
  10586. arrayBuffer = indices;
  10587. }
  10588. else {
  10589. //check 32 bit support
  10590. if (this._caps.uintIndices) {
  10591. if (indices instanceof Uint32Array) {
  10592. arrayBuffer = indices;
  10593. need32Bits = true;
  10594. }
  10595. else {
  10596. //number[] or Int32Array, check if 32 bit is necessary
  10597. for (var index = 0; index < indices.length; index++) {
  10598. if (indices[index] > 65535) {
  10599. need32Bits = true;
  10600. break;
  10601. }
  10602. }
  10603. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10604. }
  10605. }
  10606. else {
  10607. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  10608. arrayBuffer = new Uint16Array(indices);
  10609. }
  10610. }
  10611. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  10612. this._resetIndexBufferBinding();
  10613. vbo.references = 1;
  10614. vbo.is32Bits = need32Bits;
  10615. return vbo;
  10616. };
  10617. Engine.prototype.bindArrayBuffer = function (buffer) {
  10618. if (!this._vaoRecordInProgress) {
  10619. this._unbindVertexArrayObject();
  10620. }
  10621. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  10622. };
  10623. Engine.prototype.bindUniformBuffer = function (buffer) {
  10624. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  10625. };
  10626. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  10627. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  10628. };
  10629. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  10630. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  10631. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  10632. };
  10633. ;
  10634. Engine.prototype.bindIndexBuffer = function (buffer) {
  10635. if (!this._vaoRecordInProgress) {
  10636. this._unbindVertexArrayObject();
  10637. }
  10638. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  10639. };
  10640. Engine.prototype.bindBuffer = function (buffer, target) {
  10641. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  10642. this._gl.bindBuffer(target, buffer);
  10643. this._currentBoundBuffer[target] = buffer;
  10644. }
  10645. };
  10646. Engine.prototype.updateArrayBuffer = function (data) {
  10647. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10648. };
  10649. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  10650. var pointer = this._currentBufferPointers[indx];
  10651. var changed = false;
  10652. if (!pointer.active) {
  10653. changed = true;
  10654. pointer.active = true;
  10655. pointer.index = indx;
  10656. pointer.size = size;
  10657. pointer.type = type;
  10658. pointer.normalized = normalized;
  10659. pointer.stride = stride;
  10660. pointer.offset = offset;
  10661. pointer.buffer = buffer;
  10662. }
  10663. else {
  10664. if (pointer.buffer !== buffer) {
  10665. pointer.buffer = buffer;
  10666. changed = true;
  10667. }
  10668. if (pointer.size !== size) {
  10669. pointer.size = size;
  10670. changed = true;
  10671. }
  10672. if (pointer.type !== type) {
  10673. pointer.type = type;
  10674. changed = true;
  10675. }
  10676. if (pointer.normalized !== normalized) {
  10677. pointer.normalized = normalized;
  10678. changed = true;
  10679. }
  10680. if (pointer.stride !== stride) {
  10681. pointer.stride = stride;
  10682. changed = true;
  10683. }
  10684. if (pointer.offset !== offset) {
  10685. pointer.offset = offset;
  10686. changed = true;
  10687. }
  10688. }
  10689. if (changed || this._vaoRecordInProgress) {
  10690. this.bindArrayBuffer(buffer);
  10691. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  10692. }
  10693. };
  10694. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  10695. if (indexBuffer == null) {
  10696. return;
  10697. }
  10698. if (this._cachedIndexBuffer !== indexBuffer) {
  10699. this._cachedIndexBuffer = indexBuffer;
  10700. this.bindIndexBuffer(indexBuffer);
  10701. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  10702. }
  10703. };
  10704. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  10705. var attributes = effect.getAttributesNames();
  10706. if (!this._vaoRecordInProgress) {
  10707. this._unbindVertexArrayObject();
  10708. }
  10709. this.unbindAllAttributes();
  10710. for (var index = 0; index < attributes.length; index++) {
  10711. var order = effect.getAttributeLocation(index);
  10712. if (order >= 0) {
  10713. var vertexBuffer = vertexBuffers[attributes[index]];
  10714. if (!vertexBuffer) {
  10715. continue;
  10716. }
  10717. this._gl.enableVertexAttribArray(order);
  10718. if (!this._vaoRecordInProgress) {
  10719. this._vertexAttribArraysEnabled[order] = true;
  10720. }
  10721. var buffer = vertexBuffer.getBuffer();
  10722. if (buffer) {
  10723. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  10724. if (vertexBuffer.getIsInstanced()) {
  10725. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  10726. if (!this._vaoRecordInProgress) {
  10727. this._currentInstanceLocations.push(order);
  10728. this._currentInstanceBuffers.push(buffer);
  10729. }
  10730. }
  10731. }
  10732. }
  10733. }
  10734. };
  10735. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  10736. var vao = this._gl.createVertexArray();
  10737. this._vaoRecordInProgress = true;
  10738. this._gl.bindVertexArray(vao);
  10739. this._mustWipeVertexAttributes = true;
  10740. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10741. this.bindIndexBuffer(indexBuffer);
  10742. this._vaoRecordInProgress = false;
  10743. this._gl.bindVertexArray(null);
  10744. return vao;
  10745. };
  10746. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  10747. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  10748. this._cachedVertexArrayObject = vertexArrayObject;
  10749. this._gl.bindVertexArray(vertexArrayObject);
  10750. this._cachedVertexBuffers = null;
  10751. this._cachedIndexBuffer = null;
  10752. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  10753. this._mustWipeVertexAttributes = true;
  10754. }
  10755. };
  10756. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  10757. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  10758. this._cachedVertexBuffers = vertexBuffer;
  10759. this._cachedEffectForVertexBuffers = effect;
  10760. var attributesCount = effect.getAttributesCount();
  10761. this._unbindVertexArrayObject();
  10762. this.unbindAllAttributes();
  10763. var offset = 0;
  10764. for (var index = 0; index < attributesCount; index++) {
  10765. if (index < vertexDeclaration.length) {
  10766. var order = effect.getAttributeLocation(index);
  10767. if (order >= 0) {
  10768. this._gl.enableVertexAttribArray(order);
  10769. this._vertexAttribArraysEnabled[order] = true;
  10770. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  10771. }
  10772. offset += vertexDeclaration[index] * 4;
  10773. }
  10774. }
  10775. }
  10776. this._bindIndexBufferWithCache(indexBuffer);
  10777. };
  10778. Engine.prototype._unbindVertexArrayObject = function () {
  10779. if (!this._cachedVertexArrayObject) {
  10780. return;
  10781. }
  10782. this._cachedVertexArrayObject = null;
  10783. this._gl.bindVertexArray(null);
  10784. };
  10785. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  10786. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  10787. this._cachedVertexBuffers = vertexBuffers;
  10788. this._cachedEffectForVertexBuffers = effect;
  10789. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10790. }
  10791. this._bindIndexBufferWithCache(indexBuffer);
  10792. };
  10793. Engine.prototype.unbindInstanceAttributes = function () {
  10794. var boundBuffer;
  10795. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  10796. var instancesBuffer = this._currentInstanceBuffers[i];
  10797. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  10798. boundBuffer = instancesBuffer;
  10799. this.bindArrayBuffer(instancesBuffer);
  10800. }
  10801. var offsetLocation = this._currentInstanceLocations[i];
  10802. this._gl.vertexAttribDivisor(offsetLocation, 0);
  10803. }
  10804. this._currentInstanceBuffers.length = 0;
  10805. this._currentInstanceLocations.length = 0;
  10806. };
  10807. Engine.prototype.releaseVertexArrayObject = function (vao) {
  10808. this._gl.deleteVertexArray(vao);
  10809. };
  10810. Engine.prototype._releaseBuffer = function (buffer) {
  10811. buffer.references--;
  10812. if (buffer.references === 0) {
  10813. this._gl.deleteBuffer(buffer);
  10814. return true;
  10815. }
  10816. return false;
  10817. };
  10818. Engine.prototype.createInstancesBuffer = function (capacity) {
  10819. var buffer = this._gl.createBuffer();
  10820. if (!buffer) {
  10821. throw new Error("Unable to create instance buffer");
  10822. }
  10823. buffer.capacity = capacity;
  10824. this.bindArrayBuffer(buffer);
  10825. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  10826. return buffer;
  10827. };
  10828. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  10829. this._gl.deleteBuffer(buffer);
  10830. };
  10831. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  10832. this.bindArrayBuffer(instancesBuffer);
  10833. if (data) {
  10834. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10835. }
  10836. if (offsetLocations[0].index !== undefined) {
  10837. var stride = 0;
  10838. for (var i = 0; i < offsetLocations.length; i++) {
  10839. var ai = offsetLocations[i];
  10840. stride += ai.attributeSize * 4;
  10841. }
  10842. for (var i = 0; i < offsetLocations.length; i++) {
  10843. var ai = offsetLocations[i];
  10844. if (!this._vertexAttribArraysEnabled[ai.index]) {
  10845. this._gl.enableVertexAttribArray(ai.index);
  10846. this._vertexAttribArraysEnabled[ai.index] = true;
  10847. }
  10848. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  10849. this._gl.vertexAttribDivisor(ai.index, 1);
  10850. this._currentInstanceLocations.push(ai.index);
  10851. this._currentInstanceBuffers.push(instancesBuffer);
  10852. }
  10853. }
  10854. else {
  10855. for (var index = 0; index < 4; index++) {
  10856. var offsetLocation = offsetLocations[index];
  10857. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  10858. this._gl.enableVertexAttribArray(offsetLocation);
  10859. this._vertexAttribArraysEnabled[offsetLocation] = true;
  10860. }
  10861. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  10862. this._gl.vertexAttribDivisor(offsetLocation, 1);
  10863. this._currentInstanceLocations.push(offsetLocation);
  10864. this._currentInstanceBuffers.push(instancesBuffer);
  10865. }
  10866. }
  10867. };
  10868. Engine.prototype.applyStates = function () {
  10869. this._depthCullingState.apply(this._gl);
  10870. this._stencilState.apply(this._gl);
  10871. this._alphaState.apply(this._gl);
  10872. };
  10873. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  10874. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  10875. };
  10876. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  10877. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  10878. };
  10879. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  10880. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  10881. };
  10882. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  10883. // Apply states
  10884. this.applyStates();
  10885. this._drawCalls.addCount(1, false);
  10886. // Render
  10887. var drawMode = this.DrawMode(fillMode);
  10888. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  10889. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  10890. if (instancesCount) {
  10891. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  10892. }
  10893. else {
  10894. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  10895. }
  10896. };
  10897. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  10898. // Apply states
  10899. this.applyStates();
  10900. this._drawCalls.addCount(1, false);
  10901. var drawMode = this.DrawMode(fillMode);
  10902. if (instancesCount) {
  10903. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  10904. }
  10905. else {
  10906. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  10907. }
  10908. };
  10909. Engine.prototype.DrawMode = function (fillMode) {
  10910. switch (fillMode) {
  10911. // Triangle views
  10912. case BABYLON.Material.TriangleFillMode:
  10913. return this._gl.TRIANGLES;
  10914. case BABYLON.Material.PointFillMode:
  10915. return this._gl.POINTS;
  10916. case BABYLON.Material.WireFrameFillMode:
  10917. return this._gl.LINES;
  10918. // Draw modes
  10919. case BABYLON.Material.PointListDrawMode:
  10920. return this._gl.POINTS;
  10921. case BABYLON.Material.LineListDrawMode:
  10922. return this._gl.LINES;
  10923. case BABYLON.Material.LineLoopDrawMode:
  10924. return this._gl.LINE_LOOP;
  10925. case BABYLON.Material.LineStripDrawMode:
  10926. return this._gl.LINE_STRIP;
  10927. case BABYLON.Material.TriangleStripDrawMode:
  10928. return this._gl.TRIANGLE_STRIP;
  10929. case BABYLON.Material.TriangleFanDrawMode:
  10930. return this._gl.TRIANGLE_FAN;
  10931. default:
  10932. return this._gl.TRIANGLES;
  10933. }
  10934. };
  10935. // Shaders
  10936. Engine.prototype._releaseEffect = function (effect) {
  10937. if (this._compiledEffects[effect._key]) {
  10938. delete this._compiledEffects[effect._key];
  10939. this._deleteProgram(effect.getProgram());
  10940. }
  10941. };
  10942. Engine.prototype._deleteProgram = function (program) {
  10943. if (program) {
  10944. program.__SPECTOR_rebuildProgram = null;
  10945. if (program.transformFeedback) {
  10946. this.deleteTransformFeedback(program.transformFeedback);
  10947. program.transformFeedback = null;
  10948. }
  10949. this._gl.deleteProgram(program);
  10950. }
  10951. };
  10952. /**
  10953. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  10954. * @param samplers An array of string used to represent textures
  10955. */
  10956. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  10957. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  10958. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  10959. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  10960. if (this._compiledEffects[name]) {
  10961. var compiledEffect = this._compiledEffects[name];
  10962. if (onCompiled && compiledEffect.isReady()) {
  10963. onCompiled(compiledEffect);
  10964. }
  10965. return compiledEffect;
  10966. }
  10967. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  10968. effect._key = name;
  10969. this._compiledEffects[name] = effect;
  10970. return effect;
  10971. };
  10972. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  10973. if (uniformsNames === void 0) { uniformsNames = []; }
  10974. if (samplers === void 0) { samplers = []; }
  10975. if (defines === void 0) { defines = ""; }
  10976. return this.createEffect({
  10977. vertex: "particles",
  10978. fragmentElement: fragmentName
  10979. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  10980. };
  10981. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  10982. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10983. context = context || this._gl;
  10984. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  10985. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  10986. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10987. };
  10988. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  10989. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10990. context = context || this._gl;
  10991. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  10992. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  10993. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  10994. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  10995. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10996. this.onAfterShaderCompilationObservable.notifyObservers(this);
  10997. return program;
  10998. };
  10999. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  11000. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11001. var shaderProgram = context.createProgram();
  11002. if (!shaderProgram) {
  11003. throw new Error("Unable to create program");
  11004. }
  11005. context.attachShader(shaderProgram, vertexShader);
  11006. context.attachShader(shaderProgram, fragmentShader);
  11007. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11008. var transformFeedback = this.createTransformFeedback();
  11009. this.bindTransformFeedback(transformFeedback);
  11010. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  11011. shaderProgram.transformFeedback = transformFeedback;
  11012. }
  11013. context.linkProgram(shaderProgram);
  11014. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11015. this.bindTransformFeedback(null);
  11016. }
  11017. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11018. if (!linked) {
  11019. context.validateProgram(shaderProgram);
  11020. var error = context.getProgramInfoLog(shaderProgram);
  11021. if (error) {
  11022. throw new Error(error);
  11023. }
  11024. }
  11025. context.deleteShader(vertexShader);
  11026. context.deleteShader(fragmentShader);
  11027. return shaderProgram;
  11028. };
  11029. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11030. var results = new Array();
  11031. for (var index = 0; index < uniformsNames.length; index++) {
  11032. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11033. }
  11034. return results;
  11035. };
  11036. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11037. var results = [];
  11038. for (var index = 0; index < attributesNames.length; index++) {
  11039. try {
  11040. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11041. }
  11042. catch (e) {
  11043. results.push(-1);
  11044. }
  11045. }
  11046. return results;
  11047. };
  11048. Engine.prototype.enableEffect = function (effect) {
  11049. if (!effect) {
  11050. return;
  11051. }
  11052. // Use program
  11053. this.bindSamplers(effect);
  11054. this._currentEffect = effect;
  11055. if (effect.onBind) {
  11056. effect.onBind(effect);
  11057. }
  11058. effect.onBindObservable.notifyObservers(effect);
  11059. };
  11060. Engine.prototype.setIntArray = function (uniform, array) {
  11061. if (!uniform)
  11062. return;
  11063. this._gl.uniform1iv(uniform, array);
  11064. };
  11065. Engine.prototype.setIntArray2 = function (uniform, array) {
  11066. if (!uniform || array.length % 2 !== 0)
  11067. return;
  11068. this._gl.uniform2iv(uniform, array);
  11069. };
  11070. Engine.prototype.setIntArray3 = function (uniform, array) {
  11071. if (!uniform || array.length % 3 !== 0)
  11072. return;
  11073. this._gl.uniform3iv(uniform, array);
  11074. };
  11075. Engine.prototype.setIntArray4 = function (uniform, array) {
  11076. if (!uniform || array.length % 4 !== 0)
  11077. return;
  11078. this._gl.uniform4iv(uniform, array);
  11079. };
  11080. Engine.prototype.setFloatArray = function (uniform, array) {
  11081. if (!uniform)
  11082. return;
  11083. this._gl.uniform1fv(uniform, array);
  11084. };
  11085. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11086. if (!uniform || array.length % 2 !== 0)
  11087. return;
  11088. this._gl.uniform2fv(uniform, array);
  11089. };
  11090. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11091. if (!uniform || array.length % 3 !== 0)
  11092. return;
  11093. this._gl.uniform3fv(uniform, array);
  11094. };
  11095. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11096. if (!uniform || array.length % 4 !== 0)
  11097. return;
  11098. this._gl.uniform4fv(uniform, array);
  11099. };
  11100. Engine.prototype.setArray = function (uniform, array) {
  11101. if (!uniform)
  11102. return;
  11103. this._gl.uniform1fv(uniform, array);
  11104. };
  11105. Engine.prototype.setArray2 = function (uniform, array) {
  11106. if (!uniform || array.length % 2 !== 0)
  11107. return;
  11108. this._gl.uniform2fv(uniform, array);
  11109. };
  11110. Engine.prototype.setArray3 = function (uniform, array) {
  11111. if (!uniform || array.length % 3 !== 0)
  11112. return;
  11113. this._gl.uniform3fv(uniform, array);
  11114. };
  11115. Engine.prototype.setArray4 = function (uniform, array) {
  11116. if (!uniform || array.length % 4 !== 0)
  11117. return;
  11118. this._gl.uniform4fv(uniform, array);
  11119. };
  11120. Engine.prototype.setMatrices = function (uniform, matrices) {
  11121. if (!uniform)
  11122. return;
  11123. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11124. };
  11125. Engine.prototype.setMatrix = function (uniform, matrix) {
  11126. if (!uniform)
  11127. return;
  11128. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11129. };
  11130. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11131. if (!uniform)
  11132. return;
  11133. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11134. };
  11135. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11136. if (!uniform)
  11137. return;
  11138. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11139. };
  11140. Engine.prototype.setInt = function (uniform, value) {
  11141. if (!uniform)
  11142. return;
  11143. this._gl.uniform1i(uniform, value);
  11144. };
  11145. Engine.prototype.setFloat = function (uniform, value) {
  11146. if (!uniform)
  11147. return;
  11148. this._gl.uniform1f(uniform, value);
  11149. };
  11150. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11151. if (!uniform)
  11152. return;
  11153. this._gl.uniform2f(uniform, x, y);
  11154. };
  11155. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11156. if (!uniform)
  11157. return;
  11158. this._gl.uniform3f(uniform, x, y, z);
  11159. };
  11160. Engine.prototype.setBool = function (uniform, bool) {
  11161. if (!uniform)
  11162. return;
  11163. this._gl.uniform1i(uniform, bool);
  11164. };
  11165. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11166. if (!uniform)
  11167. return;
  11168. this._gl.uniform4f(uniform, x, y, z, w);
  11169. };
  11170. Engine.prototype.setColor3 = function (uniform, color3) {
  11171. if (!uniform)
  11172. return;
  11173. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11174. };
  11175. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11176. if (!uniform)
  11177. return;
  11178. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11179. };
  11180. // States
  11181. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11182. if (zOffset === void 0) { zOffset = 0; }
  11183. if (reverseSide === void 0) { reverseSide = false; }
  11184. // Culling
  11185. if (this._depthCullingState.cull !== culling || force) {
  11186. this._depthCullingState.cull = culling;
  11187. }
  11188. // Cull face
  11189. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11190. if (this._depthCullingState.cullFace !== cullFace || force) {
  11191. this._depthCullingState.cullFace = cullFace;
  11192. }
  11193. // Z offset
  11194. this.setZOffset(zOffset);
  11195. // Front face
  11196. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11197. if (this._depthCullingState.frontFace !== frontFace || force) {
  11198. this._depthCullingState.frontFace = frontFace;
  11199. }
  11200. };
  11201. Engine.prototype.setZOffset = function (value) {
  11202. this._depthCullingState.zOffset = value;
  11203. };
  11204. Engine.prototype.getZOffset = function () {
  11205. return this._depthCullingState.zOffset;
  11206. };
  11207. Engine.prototype.setDepthBuffer = function (enable) {
  11208. this._depthCullingState.depthTest = enable;
  11209. };
  11210. Engine.prototype.getDepthWrite = function () {
  11211. return this._depthCullingState.depthMask;
  11212. };
  11213. Engine.prototype.setDepthWrite = function (enable) {
  11214. this._depthCullingState.depthMask = enable;
  11215. };
  11216. Engine.prototype.setColorWrite = function (enable) {
  11217. this._gl.colorMask(enable, enable, enable, enable);
  11218. this._colorWrite = enable;
  11219. };
  11220. Engine.prototype.getColorWrite = function () {
  11221. return this._colorWrite;
  11222. };
  11223. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11224. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11225. };
  11226. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11227. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11228. if (this._alphaMode === mode) {
  11229. return;
  11230. }
  11231. switch (mode) {
  11232. case Engine.ALPHA_DISABLE:
  11233. this._alphaState.alphaBlend = false;
  11234. break;
  11235. case Engine.ALPHA_PREMULTIPLIED:
  11236. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11237. this._alphaState.alphaBlend = true;
  11238. break;
  11239. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11240. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11241. this._alphaState.alphaBlend = true;
  11242. break;
  11243. case Engine.ALPHA_COMBINE:
  11244. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11245. this._alphaState.alphaBlend = true;
  11246. break;
  11247. case Engine.ALPHA_ONEONE:
  11248. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11249. this._alphaState.alphaBlend = true;
  11250. break;
  11251. case Engine.ALPHA_ADD:
  11252. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11253. this._alphaState.alphaBlend = true;
  11254. break;
  11255. case Engine.ALPHA_SUBTRACT:
  11256. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11257. this._alphaState.alphaBlend = true;
  11258. break;
  11259. case Engine.ALPHA_MULTIPLY:
  11260. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11261. this._alphaState.alphaBlend = true;
  11262. break;
  11263. case Engine.ALPHA_MAXIMIZED:
  11264. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11265. this._alphaState.alphaBlend = true;
  11266. break;
  11267. case Engine.ALPHA_INTERPOLATE:
  11268. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11269. this._alphaState.alphaBlend = true;
  11270. break;
  11271. case Engine.ALPHA_SCREENMODE:
  11272. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11273. this._alphaState.alphaBlend = true;
  11274. break;
  11275. }
  11276. if (!noDepthWriteChange) {
  11277. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11278. }
  11279. this._alphaMode = mode;
  11280. };
  11281. Engine.prototype.getAlphaMode = function () {
  11282. return this._alphaMode;
  11283. };
  11284. // Textures
  11285. Engine.prototype.wipeCaches = function (bruteForce) {
  11286. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11287. return;
  11288. }
  11289. this._currentEffect = null;
  11290. // 6/8/2017: deltakosh: Should not be required anymore.
  11291. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11292. if (bruteForce) {
  11293. this.resetTextureCache();
  11294. this._currentProgram = null;
  11295. this._stencilState.reset();
  11296. this._depthCullingState.reset();
  11297. this.setDepthFunctionToLessOrEqual();
  11298. this._alphaState.reset();
  11299. }
  11300. this._resetVertexBufferBinding();
  11301. this._cachedIndexBuffer = null;
  11302. this._cachedEffectForVertexBuffers = null;
  11303. this._unbindVertexArrayObject();
  11304. this.bindIndexBuffer(null);
  11305. };
  11306. /**
  11307. * Set the compressed texture format to use, based on the formats you have, and the formats
  11308. * supported by the hardware / browser.
  11309. *
  11310. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11311. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11312. * to API arguments needed to compressed textures. This puts the burden on the container
  11313. * generator to house the arcane code for determining these for current & future formats.
  11314. *
  11315. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11316. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11317. *
  11318. * Note: The result of this call is not taken into account when a texture is base64.
  11319. *
  11320. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11321. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11322. *
  11323. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11324. * @returns The extension selected.
  11325. */
  11326. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11327. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11328. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11329. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11330. return this._textureFormatInUse = this._texturesSupported[i];
  11331. }
  11332. }
  11333. }
  11334. // actively set format to nothing, to allow this to be called more than once
  11335. // and possibly fail the 2nd time
  11336. this._textureFormatInUse = null;
  11337. return null;
  11338. };
  11339. Engine.prototype._createTexture = function () {
  11340. var texture = this._gl.createTexture();
  11341. if (!texture) {
  11342. throw new Error("Unable to create texture");
  11343. }
  11344. return texture;
  11345. };
  11346. /**
  11347. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11348. * @param {string} urlArg- This contains one of the following:
  11349. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11350. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11351. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11352. *
  11353. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11354. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11355. * @param {Scene} scene- Needed for loading to the correct scene.
  11356. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11357. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11358. * @param {callback} onError- Optional callback to be called upon failure.
  11359. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11360. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11361. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11362. *
  11363. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11364. */
  11365. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11366. var _this = this;
  11367. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11368. if (onLoad === void 0) { onLoad = null; }
  11369. if (onError === void 0) { onError = null; }
  11370. if (buffer === void 0) { buffer = null; }
  11371. if (fallBack === void 0) { fallBack = null; }
  11372. if (format === void 0) { format = null; }
  11373. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11374. var fromData = url.substr(0, 5) === "data:";
  11375. var fromBlob = url.substr(0, 5) === "blob:";
  11376. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11377. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11378. // establish the file extension, if possible
  11379. var lastDot = url.lastIndexOf('.');
  11380. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11381. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  11382. var isTGA = (extension === ".tga");
  11383. // determine if a ktx file should be substituted
  11384. var isKTX = false;
  11385. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11386. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11387. isKTX = true;
  11388. }
  11389. if (scene) {
  11390. scene._addPendingData(texture);
  11391. }
  11392. texture.url = url;
  11393. texture.generateMipMaps = !noMipmap;
  11394. texture.samplingMode = samplingMode;
  11395. texture.invertY = invertY;
  11396. if (!this._doNotHandleContextLost) {
  11397. // Keep a link to the buffer only if we plan to handle context lost
  11398. texture._buffer = buffer;
  11399. }
  11400. var onLoadObserver = null;
  11401. if (onLoad && !fallBack) {
  11402. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11403. }
  11404. if (!fallBack)
  11405. this._internalTexturesCache.push(texture);
  11406. var onerror = function (message, exception) {
  11407. if (scene) {
  11408. scene._removePendingData(texture);
  11409. }
  11410. if (onLoadObserver) {
  11411. texture.onLoadedObservable.remove(onLoadObserver);
  11412. }
  11413. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11414. if (isKTX) {
  11415. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11416. }
  11417. else if (BABYLON.Tools.UseFallbackTexture) {
  11418. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11419. }
  11420. if (onError) {
  11421. onError(message || "Unknown error", exception);
  11422. }
  11423. };
  11424. var callback = null;
  11425. // processing for non-image formats
  11426. if (isKTX || isTGA || isDDS) {
  11427. if (isKTX) {
  11428. callback = function (data) {
  11429. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11430. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11431. ktx.uploadLevels(_this._gl, !noMipmap);
  11432. return false;
  11433. }, samplingMode);
  11434. };
  11435. }
  11436. else if (isTGA) {
  11437. callback = function (arrayBuffer) {
  11438. var data = new Uint8Array(arrayBuffer);
  11439. var header = BABYLON.TGATools.GetTGAHeader(data);
  11440. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11441. BABYLON.TGATools.UploadContent(_this._gl, data);
  11442. return false;
  11443. }, samplingMode);
  11444. };
  11445. }
  11446. else if (isDDS) {
  11447. callback = function (data) {
  11448. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11449. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11450. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11451. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11452. return false;
  11453. }, samplingMode);
  11454. };
  11455. }
  11456. if (!buffer) {
  11457. this._loadFile(url, function (data) {
  11458. if (callback) {
  11459. callback(data);
  11460. }
  11461. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11462. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11463. });
  11464. }
  11465. else {
  11466. if (callback) {
  11467. callback(buffer);
  11468. }
  11469. }
  11470. // image format processing
  11471. }
  11472. else {
  11473. var onload = function (img) {
  11474. if (fromBlob && !_this._doNotHandleContextLost) {
  11475. // We need to store the image if we need to rebuild the texture
  11476. // in case of a webgl context lost
  11477. texture._buffer = img;
  11478. }
  11479. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  11480. var gl = _this._gl;
  11481. var isPot = (img.width === potWidth && img.height === potHeight);
  11482. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  11483. if (isPot) {
  11484. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11485. return false;
  11486. }
  11487. // Using shaders to rescale because canvas.drawImage is lossy
  11488. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11489. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  11490. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11491. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11492. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11493. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11494. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11495. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  11496. _this._releaseTexture(source);
  11497. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11498. continuationCallback();
  11499. });
  11500. return true;
  11501. }, samplingMode);
  11502. };
  11503. if (!fromData || isBase64)
  11504. if (buffer instanceof HTMLImageElement) {
  11505. onload(buffer);
  11506. }
  11507. else {
  11508. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11509. }
  11510. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  11511. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  11512. else
  11513. onload(buffer);
  11514. }
  11515. return texture;
  11516. };
  11517. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  11518. var _this = this;
  11519. var rtt = this.createRenderTargetTexture({
  11520. width: destination.width,
  11521. height: destination.height,
  11522. }, {
  11523. generateMipMaps: false,
  11524. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  11525. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  11526. generateDepthBuffer: false,
  11527. generateStencilBuffer: false
  11528. });
  11529. if (!this._rescalePostProcess) {
  11530. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  11531. }
  11532. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  11533. _this._rescalePostProcess.onApply = function (effect) {
  11534. effect._bindTexture("textureSampler", source);
  11535. };
  11536. var hostingScene = scene;
  11537. if (!hostingScene) {
  11538. hostingScene = _this.scenes[_this.scenes.length - 1];
  11539. }
  11540. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  11541. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  11542. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  11543. _this.unBindFramebuffer(rtt);
  11544. _this._releaseTexture(rtt);
  11545. if (onComplete) {
  11546. onComplete();
  11547. }
  11548. });
  11549. };
  11550. Engine.prototype._getInternalFormat = function (format) {
  11551. var internalFormat = this._gl.RGBA;
  11552. switch (format) {
  11553. case Engine.TEXTUREFORMAT_ALPHA:
  11554. internalFormat = this._gl.ALPHA;
  11555. break;
  11556. case Engine.TEXTUREFORMAT_LUMINANCE:
  11557. internalFormat = this._gl.LUMINANCE;
  11558. break;
  11559. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  11560. internalFormat = this._gl.LUMINANCE_ALPHA;
  11561. break;
  11562. case Engine.TEXTUREFORMAT_RGB:
  11563. internalFormat = this._gl.RGB;
  11564. break;
  11565. case Engine.TEXTUREFORMAT_RGBA:
  11566. internalFormat = this._gl.RGBA;
  11567. break;
  11568. }
  11569. return internalFormat;
  11570. };
  11571. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  11572. if (compression === void 0) { compression = null; }
  11573. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11574. if (!texture) {
  11575. return;
  11576. }
  11577. var internalFormat = this._getInternalFormat(format);
  11578. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11579. var textureType = this._getWebGLTextureType(type);
  11580. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11581. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11582. if (!this._doNotHandleContextLost) {
  11583. texture._bufferView = data;
  11584. texture.format = format;
  11585. texture.type = type;
  11586. texture.invertY = invertY;
  11587. texture._compression = compression;
  11588. }
  11589. if (texture.width % 4 !== 0) {
  11590. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11591. }
  11592. if (compression && data) {
  11593. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  11594. }
  11595. else {
  11596. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  11597. }
  11598. if (texture.generateMipMaps) {
  11599. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11600. }
  11601. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11602. // this.resetTextureCache();
  11603. texture.isReady = true;
  11604. };
  11605. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  11606. if (compression === void 0) { compression = null; }
  11607. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11608. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  11609. texture.baseWidth = width;
  11610. texture.baseHeight = height;
  11611. texture.width = width;
  11612. texture.height = height;
  11613. texture.format = format;
  11614. texture.generateMipMaps = generateMipMaps;
  11615. texture.samplingMode = samplingMode;
  11616. texture.invertY = invertY;
  11617. texture._compression = compression;
  11618. texture.type = type;
  11619. if (!this._doNotHandleContextLost) {
  11620. texture._bufferView = data;
  11621. }
  11622. this.updateRawTexture(texture, data, format, invertY, compression, type);
  11623. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11624. // Filters
  11625. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11626. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11627. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11628. if (generateMipMaps) {
  11629. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11630. }
  11631. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11632. this._internalTexturesCache.push(texture);
  11633. return texture;
  11634. };
  11635. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  11636. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  11637. texture.baseWidth = width;
  11638. texture.baseHeight = height;
  11639. if (generateMipMaps) {
  11640. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  11641. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  11642. }
  11643. // this.resetTextureCache();
  11644. texture.width = width;
  11645. texture.height = height;
  11646. texture.isReady = false;
  11647. texture.generateMipMaps = generateMipMaps;
  11648. texture.samplingMode = samplingMode;
  11649. this.updateTextureSamplingMode(samplingMode, texture);
  11650. this._internalTexturesCache.push(texture);
  11651. return texture;
  11652. };
  11653. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  11654. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  11655. if (texture.isCube) {
  11656. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11657. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11658. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11659. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11660. }
  11661. else if (texture.is3D) {
  11662. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11663. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11664. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11665. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11666. }
  11667. else {
  11668. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11669. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11670. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11671. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11672. }
  11673. texture.samplingMode = samplingMode;
  11674. };
  11675. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  11676. if (premulAlpha === void 0) { premulAlpha = false; }
  11677. if (!texture) {
  11678. return;
  11679. }
  11680. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11681. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  11682. if (premulAlpha) {
  11683. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  11684. }
  11685. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  11686. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  11687. if (texture.generateMipMaps) {
  11688. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11689. }
  11690. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11691. if (premulAlpha) {
  11692. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  11693. }
  11694. texture.isReady = true;
  11695. };
  11696. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  11697. if (!texture || texture._isDisabled) {
  11698. return;
  11699. }
  11700. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11701. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  11702. try {
  11703. // Testing video texture support
  11704. if (this._videoTextureSupported === undefined) {
  11705. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11706. if (this._gl.getError() !== 0) {
  11707. this._videoTextureSupported = false;
  11708. }
  11709. else {
  11710. this._videoTextureSupported = true;
  11711. }
  11712. }
  11713. // Copy video through the current working canvas if video texture is not supported
  11714. if (!this._videoTextureSupported) {
  11715. if (!texture._workingCanvas) {
  11716. texture._workingCanvas = document.createElement("canvas");
  11717. var context = texture._workingCanvas.getContext("2d");
  11718. if (!context) {
  11719. throw new Error("Unable to get 2d context");
  11720. }
  11721. texture._workingContext = context;
  11722. texture._workingCanvas.width = texture.width;
  11723. texture._workingCanvas.height = texture.height;
  11724. }
  11725. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  11726. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  11727. }
  11728. else {
  11729. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11730. }
  11731. if (texture.generateMipMaps) {
  11732. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11733. }
  11734. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11735. // this.resetTextureCache();
  11736. texture.isReady = true;
  11737. }
  11738. catch (ex) {
  11739. // Something unexpected
  11740. // Let's disable the texture
  11741. texture._isDisabled = true;
  11742. }
  11743. };
  11744. Engine.prototype.createRenderTargetTexture = function (size, options) {
  11745. var fullOptions = new RenderTargetCreationOptions();
  11746. if (options !== undefined && typeof options === "object") {
  11747. fullOptions.generateMipMaps = options.generateMipMaps;
  11748. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11749. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  11750. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  11751. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  11752. }
  11753. else {
  11754. fullOptions.generateMipMaps = options;
  11755. fullOptions.generateDepthBuffer = true;
  11756. fullOptions.generateStencilBuffer = false;
  11757. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11758. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11759. }
  11760. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11761. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11762. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11763. }
  11764. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11765. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11766. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11767. }
  11768. var gl = this._gl;
  11769. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11770. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11771. var width = size.width || size;
  11772. var height = size.height || size;
  11773. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  11774. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11775. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11776. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11777. }
  11778. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11779. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11780. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11781. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11782. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  11783. // Create the framebuffer
  11784. var framebuffer = gl.createFramebuffer();
  11785. this.bindUnboundFramebuffer(framebuffer);
  11786. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11787. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  11788. if (fullOptions.generateMipMaps) {
  11789. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11790. }
  11791. // Unbind
  11792. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11793. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11794. this.bindUnboundFramebuffer(null);
  11795. texture._framebuffer = framebuffer;
  11796. texture.baseWidth = width;
  11797. texture.baseHeight = height;
  11798. texture.width = width;
  11799. texture.height = height;
  11800. texture.isReady = true;
  11801. texture.samples = 1;
  11802. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  11803. texture.samplingMode = fullOptions.samplingMode;
  11804. texture.type = fullOptions.type;
  11805. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  11806. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  11807. // this.resetTextureCache();
  11808. this._internalTexturesCache.push(texture);
  11809. return texture;
  11810. };
  11811. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  11812. var generateMipMaps = false;
  11813. var generateDepthBuffer = true;
  11814. var generateStencilBuffer = false;
  11815. var generateDepthTexture = false;
  11816. var textureCount = 1;
  11817. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  11818. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11819. var types = [], samplingModes = [];
  11820. if (options !== undefined) {
  11821. generateMipMaps = options.generateMipMaps;
  11822. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11823. generateStencilBuffer = options.generateStencilBuffer;
  11824. generateDepthTexture = options.generateDepthTexture;
  11825. textureCount = options.textureCount || 1;
  11826. if (options.types) {
  11827. types = options.types;
  11828. }
  11829. if (options.samplingModes) {
  11830. samplingModes = options.samplingModes;
  11831. }
  11832. }
  11833. var gl = this._gl;
  11834. // Create the framebuffer
  11835. var framebuffer = gl.createFramebuffer();
  11836. this.bindUnboundFramebuffer(framebuffer);
  11837. var width = size.width || size;
  11838. var height = size.height || size;
  11839. var textures = [];
  11840. var attachments = [];
  11841. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  11842. for (var i = 0; i < textureCount; i++) {
  11843. var samplingMode = samplingModes[i] || defaultSamplingMode;
  11844. var type = types[i] || defaultType;
  11845. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11846. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11847. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11848. }
  11849. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11850. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11851. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11852. }
  11853. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11854. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11855. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11856. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11857. }
  11858. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11859. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11860. textures.push(texture);
  11861. attachments.push(attachment);
  11862. gl.activeTexture(gl["TEXTURE" + i]);
  11863. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  11864. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11865. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11866. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11867. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11868. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11869. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11870. if (generateMipMaps) {
  11871. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11872. }
  11873. // Unbind
  11874. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11875. texture._framebuffer = framebuffer;
  11876. texture._depthStencilBuffer = depthStencilBuffer;
  11877. texture.baseWidth = width;
  11878. texture.baseHeight = height;
  11879. texture.width = width;
  11880. texture.height = height;
  11881. texture.isReady = true;
  11882. texture.samples = 1;
  11883. texture.generateMipMaps = generateMipMaps;
  11884. texture.samplingMode = samplingMode;
  11885. texture.type = type;
  11886. texture._generateDepthBuffer = generateDepthBuffer;
  11887. texture._generateStencilBuffer = generateStencilBuffer;
  11888. texture._attachments = attachments;
  11889. this._internalTexturesCache.push(texture);
  11890. }
  11891. if (generateDepthTexture && this._caps.depthTextureExtension) {
  11892. // Depth texture
  11893. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11894. gl.activeTexture(gl.TEXTURE0);
  11895. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  11896. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11897. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11898. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11899. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11900. 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);
  11901. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  11902. depthTexture._framebuffer = framebuffer;
  11903. depthTexture.baseWidth = width;
  11904. depthTexture.baseHeight = height;
  11905. depthTexture.width = width;
  11906. depthTexture.height = height;
  11907. depthTexture.isReady = true;
  11908. depthTexture.samples = 1;
  11909. depthTexture.generateMipMaps = generateMipMaps;
  11910. depthTexture.samplingMode = gl.NEAREST;
  11911. depthTexture._generateDepthBuffer = generateDepthBuffer;
  11912. depthTexture._generateStencilBuffer = generateStencilBuffer;
  11913. textures.push(depthTexture);
  11914. this._internalTexturesCache.push(depthTexture);
  11915. }
  11916. gl.drawBuffers(attachments);
  11917. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11918. this.bindUnboundFramebuffer(null);
  11919. this.resetTextureCache();
  11920. return textures;
  11921. };
  11922. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  11923. if (samples === void 0) { samples = 1; }
  11924. var depthStencilBuffer = null;
  11925. var gl = this._gl;
  11926. // Create the depth/stencil buffer
  11927. if (generateStencilBuffer) {
  11928. depthStencilBuffer = gl.createRenderbuffer();
  11929. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11930. if (samples > 1) {
  11931. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  11932. }
  11933. else {
  11934. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  11935. }
  11936. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11937. }
  11938. else if (generateDepthBuffer) {
  11939. depthStencilBuffer = gl.createRenderbuffer();
  11940. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11941. if (samples > 1) {
  11942. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  11943. }
  11944. else {
  11945. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  11946. }
  11947. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11948. }
  11949. return depthStencilBuffer;
  11950. };
  11951. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  11952. if (this.webGLVersion < 2 || !texture) {
  11953. return 1;
  11954. }
  11955. if (texture.samples === samples) {
  11956. return samples;
  11957. }
  11958. var gl = this._gl;
  11959. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11960. // Dispose previous render buffers
  11961. if (texture._depthStencilBuffer) {
  11962. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11963. texture._depthStencilBuffer = null;
  11964. }
  11965. if (texture._MSAAFramebuffer) {
  11966. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11967. texture._MSAAFramebuffer = null;
  11968. }
  11969. if (texture._MSAARenderBuffer) {
  11970. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11971. texture._MSAARenderBuffer = null;
  11972. }
  11973. if (samples > 1) {
  11974. var framebuffer = gl.createFramebuffer();
  11975. if (!framebuffer) {
  11976. throw new Error("Unable to create multi sampled framebuffer");
  11977. }
  11978. texture._MSAAFramebuffer = framebuffer;
  11979. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  11980. var colorRenderbuffer = gl.createRenderbuffer();
  11981. if (!colorRenderbuffer) {
  11982. throw new Error("Unable to create multi sampled framebuffer");
  11983. }
  11984. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11985. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  11986. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  11987. texture._MSAARenderBuffer = colorRenderbuffer;
  11988. }
  11989. else {
  11990. this.bindUnboundFramebuffer(texture._framebuffer);
  11991. }
  11992. texture.samples = samples;
  11993. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  11994. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11995. this.bindUnboundFramebuffer(null);
  11996. return samples;
  11997. };
  11998. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  11999. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  12000. return 1;
  12001. }
  12002. if (textures[0].samples === samples) {
  12003. return samples;
  12004. }
  12005. var gl = this._gl;
  12006. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12007. // Dispose previous render buffers
  12008. if (textures[0]._depthStencilBuffer) {
  12009. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  12010. textures[0]._depthStencilBuffer = null;
  12011. }
  12012. if (textures[0]._MSAAFramebuffer) {
  12013. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12014. textures[0]._MSAAFramebuffer = null;
  12015. }
  12016. for (var i = 0; i < textures.length; i++) {
  12017. if (textures[i]._MSAARenderBuffer) {
  12018. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12019. textures[i]._MSAARenderBuffer = null;
  12020. }
  12021. }
  12022. if (samples > 1) {
  12023. var framebuffer = gl.createFramebuffer();
  12024. if (!framebuffer) {
  12025. throw new Error("Unable to create multi sampled framebuffer");
  12026. }
  12027. this.bindUnboundFramebuffer(framebuffer);
  12028. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12029. var attachments = [];
  12030. for (var i = 0; i < textures.length; i++) {
  12031. var texture = textures[i];
  12032. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12033. var colorRenderbuffer = gl.createRenderbuffer();
  12034. if (!colorRenderbuffer) {
  12035. throw new Error("Unable to create multi sampled framebuffer");
  12036. }
  12037. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12038. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12039. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12040. texture._MSAAFramebuffer = framebuffer;
  12041. texture._MSAARenderBuffer = colorRenderbuffer;
  12042. texture.samples = samples;
  12043. texture._depthStencilBuffer = depthStencilBuffer;
  12044. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12045. attachments.push(attachment);
  12046. }
  12047. gl.drawBuffers(attachments);
  12048. }
  12049. else {
  12050. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12051. }
  12052. this.bindUnboundFramebuffer(null);
  12053. return samples;
  12054. };
  12055. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12056. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12057. };
  12058. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12059. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12060. };
  12061. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12062. var gl = this._gl;
  12063. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12064. var generateMipMaps = true;
  12065. var generateDepthBuffer = true;
  12066. var generateStencilBuffer = false;
  12067. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12068. if (options !== undefined) {
  12069. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12070. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12071. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12072. if (options.samplingMode !== undefined) {
  12073. samplingMode = options.samplingMode;
  12074. }
  12075. }
  12076. texture.isCube = true;
  12077. texture.generateMipMaps = generateMipMaps;
  12078. texture.samples = 1;
  12079. texture.samplingMode = samplingMode;
  12080. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12081. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12082. for (var face = 0; face < 6; face++) {
  12083. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12084. }
  12085. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12086. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12087. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12088. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12089. // Create the framebuffer
  12090. var framebuffer = gl.createFramebuffer();
  12091. this.bindUnboundFramebuffer(framebuffer);
  12092. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12093. // Mipmaps
  12094. if (texture.generateMipMaps) {
  12095. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12096. }
  12097. // Unbind
  12098. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12099. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12100. this.bindUnboundFramebuffer(null);
  12101. texture._framebuffer = framebuffer;
  12102. texture.width = size;
  12103. texture.height = size;
  12104. texture.isReady = true;
  12105. //this.resetTextureCache();
  12106. this._internalTexturesCache.push(texture);
  12107. return texture;
  12108. };
  12109. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12110. var _this = this;
  12111. if (onLoad === void 0) { onLoad = null; }
  12112. if (onError === void 0) { onError = null; }
  12113. if (forcedExtension === void 0) { forcedExtension = null; }
  12114. var callback = function (loadData) {
  12115. if (!loadData) {
  12116. if (onLoad) {
  12117. onLoad(null);
  12118. }
  12119. return;
  12120. }
  12121. var texture = loadData.texture;
  12122. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12123. texture._lodGenerationScale = scale;
  12124. texture._lodGenerationOffset = offset;
  12125. if (_this._caps.textureLOD) {
  12126. // Do not add extra process if texture lod is supported.
  12127. if (onLoad) {
  12128. onLoad(texture);
  12129. }
  12130. return;
  12131. }
  12132. var mipSlices = 3;
  12133. var gl = _this._gl;
  12134. var width = loadData.width;
  12135. if (!width) {
  12136. return;
  12137. }
  12138. var textures = [];
  12139. for (var i = 0; i < mipSlices; i++) {
  12140. //compute LOD from even spacing in smoothness (matching shader calculation)
  12141. var smoothness = i / (mipSlices - 1);
  12142. var roughness = 1 - smoothness;
  12143. var minLODIndex = offset; // roughness = 0
  12144. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12145. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12146. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12147. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12148. glTextureFromLod.isCube = true;
  12149. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12150. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12151. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12152. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12153. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12154. if (loadData.isDDS) {
  12155. var info = loadData.info;
  12156. var data = loadData.data;
  12157. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12158. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12159. }
  12160. else {
  12161. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12162. }
  12163. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12164. // Wrap in a base texture for easy binding.
  12165. var lodTexture = new BABYLON.BaseTexture(scene);
  12166. lodTexture.isCube = true;
  12167. lodTexture._texture = glTextureFromLod;
  12168. glTextureFromLod.isReady = true;
  12169. textures.push(lodTexture);
  12170. }
  12171. texture._lodTextureHigh = textures[2];
  12172. texture._lodTextureMid = textures[1];
  12173. texture._lodTextureLow = textures[0];
  12174. if (onLoad) {
  12175. onLoad(texture);
  12176. }
  12177. };
  12178. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12179. };
  12180. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12181. var _this = this;
  12182. if (onLoad === void 0) { onLoad = null; }
  12183. if (onError === void 0) { onError = null; }
  12184. if (forcedExtension === void 0) { forcedExtension = null; }
  12185. var gl = this._gl;
  12186. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12187. texture.isCube = true;
  12188. texture.url = rootUrl;
  12189. texture.generateMipMaps = !noMipmap;
  12190. if (!this._doNotHandleContextLost) {
  12191. texture._extension = forcedExtension;
  12192. texture._files = files;
  12193. }
  12194. var isKTX = false;
  12195. var isDDS = false;
  12196. var lastDot = rootUrl.lastIndexOf('.');
  12197. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12198. if (this._textureFormatInUse) {
  12199. extension = this._textureFormatInUse;
  12200. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12201. isKTX = true;
  12202. }
  12203. else {
  12204. isDDS = (extension === ".dds");
  12205. }
  12206. var onerror = function (request, exception) {
  12207. if (onError && request) {
  12208. onError(request.status + " " + request.statusText, exception);
  12209. }
  12210. };
  12211. if (isKTX) {
  12212. this._loadFile(rootUrl, function (data) {
  12213. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12214. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12215. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12216. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12217. ktx.uploadLevels(_this._gl, !noMipmap);
  12218. _this.setCubeMapTextureParams(gl, loadMipmap);
  12219. texture.width = ktx.pixelWidth;
  12220. texture.height = ktx.pixelHeight;
  12221. texture.isReady = true;
  12222. }, undefined, undefined, true, onerror);
  12223. }
  12224. else if (isDDS) {
  12225. if (files && files.length === 6) {
  12226. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12227. var info;
  12228. var loadMipmap = false;
  12229. var width = 0;
  12230. for (var index = 0; index < imgs.length; index++) {
  12231. var data = imgs[index];
  12232. info = BABYLON.DDSTools.GetDDSInfo(data);
  12233. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12234. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12235. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12236. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12237. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12238. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12239. }
  12240. texture.width = info.width;
  12241. texture.height = info.height;
  12242. texture.type = info.textureType;
  12243. width = info.width;
  12244. }
  12245. _this.setCubeMapTextureParams(gl, loadMipmap);
  12246. texture.isReady = true;
  12247. if (onLoad) {
  12248. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12249. }
  12250. }, files, onError);
  12251. }
  12252. else {
  12253. this._loadFile(rootUrl, function (data) {
  12254. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12255. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12256. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12257. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12258. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12259. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12260. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12261. }
  12262. _this.setCubeMapTextureParams(gl, loadMipmap);
  12263. texture.width = info.width;
  12264. texture.height = info.height;
  12265. texture.isReady = true;
  12266. texture.type = info.textureType;
  12267. if (onLoad) {
  12268. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12269. }
  12270. }, undefined, undefined, true, onerror);
  12271. }
  12272. }
  12273. else {
  12274. if (!files) {
  12275. throw new Error("Cannot load cubemap because files were not defined");
  12276. }
  12277. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12278. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12279. var height = width;
  12280. _this._prepareWorkingCanvas();
  12281. if (!_this._workingCanvas || !_this._workingContext) {
  12282. return;
  12283. }
  12284. _this._workingCanvas.width = width;
  12285. _this._workingCanvas.height = height;
  12286. var faces = [
  12287. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12288. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12289. ];
  12290. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12291. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12292. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12293. for (var index = 0; index < faces.length; index++) {
  12294. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12295. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12296. }
  12297. if (!noMipmap) {
  12298. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12299. }
  12300. _this.setCubeMapTextureParams(gl, !noMipmap);
  12301. texture.width = width;
  12302. texture.height = height;
  12303. texture.isReady = true;
  12304. if (format) {
  12305. texture.format = format;
  12306. }
  12307. texture.onLoadedObservable.notifyObservers(texture);
  12308. texture.onLoadedObservable.clear();
  12309. if (onLoad) {
  12310. onLoad();
  12311. }
  12312. }, files, onError);
  12313. }
  12314. this._internalTexturesCache.push(texture);
  12315. return texture;
  12316. };
  12317. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12318. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12319. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12320. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12321. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12322. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12323. // this.resetTextureCache();
  12324. };
  12325. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12326. if (compression === void 0) { compression = null; }
  12327. if (level === void 0) { level = 0; }
  12328. texture._bufferViewArray = data;
  12329. texture.format = format;
  12330. texture.type = type;
  12331. texture.invertY = invertY;
  12332. texture._compression = compression;
  12333. var gl = this._gl;
  12334. var textureType = this._getWebGLTextureType(type);
  12335. var internalFormat = this._getInternalFormat(format);
  12336. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12337. var needConversion = false;
  12338. if (internalFormat === gl.RGB) {
  12339. internalFormat = gl.RGBA;
  12340. needConversion = true;
  12341. }
  12342. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12343. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12344. if (texture.width % 4 !== 0) {
  12345. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12346. }
  12347. // Data are known to be in +X +Y +Z -X -Y -Z
  12348. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12349. var faceData = data[faceIndex];
  12350. if (compression) {
  12351. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12352. }
  12353. else {
  12354. if (needConversion) {
  12355. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12356. }
  12357. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12358. }
  12359. }
  12360. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12361. if (isPot && texture.generateMipMaps && level === 0) {
  12362. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12363. }
  12364. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12365. // this.resetTextureCache();
  12366. texture.isReady = true;
  12367. };
  12368. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12369. if (compression === void 0) { compression = null; }
  12370. var gl = this._gl;
  12371. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12372. texture.isCube = true;
  12373. texture.generateMipMaps = generateMipMaps;
  12374. texture.format = format;
  12375. texture.type = type;
  12376. if (!this._doNotHandleContextLost) {
  12377. texture._bufferViewArray = data;
  12378. }
  12379. var textureType = this._getWebGLTextureType(type);
  12380. var internalFormat = this._getInternalFormat(format);
  12381. if (internalFormat === gl.RGB) {
  12382. internalFormat = gl.RGBA;
  12383. }
  12384. var width = size;
  12385. var height = width;
  12386. texture.width = width;
  12387. texture.height = height;
  12388. // Double check on POT to generate Mips.
  12389. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12390. if (!isPot) {
  12391. generateMipMaps = false;
  12392. }
  12393. // Upload data if needed. The texture won't be ready until then.
  12394. if (data) {
  12395. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12396. }
  12397. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12398. // Filters
  12399. if (data && generateMipMaps) {
  12400. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12401. }
  12402. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12403. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12404. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12405. }
  12406. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12407. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12408. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12409. }
  12410. else {
  12411. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12412. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12413. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12414. }
  12415. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12416. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12417. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12418. return texture;
  12419. };
  12420. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12421. var _this = this;
  12422. if (onLoad === void 0) { onLoad = null; }
  12423. if (onError === void 0) { onError = null; }
  12424. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12425. if (invertY === void 0) { invertY = false; }
  12426. var gl = this._gl;
  12427. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12428. scene._addPendingData(texture);
  12429. texture.url = url;
  12430. this._internalTexturesCache.push(texture);
  12431. var onerror = function (request, exception) {
  12432. scene._removePendingData(texture);
  12433. if (onError && request) {
  12434. onError(request.status + " " + request.statusText, exception);
  12435. }
  12436. };
  12437. var internalCallback = function (data) {
  12438. var width = texture.width;
  12439. var faceDataArrays = callback(data);
  12440. if (!faceDataArrays) {
  12441. return;
  12442. }
  12443. if (mipmmapGenerator) {
  12444. var textureType = _this._getWebGLTextureType(type);
  12445. var internalFormat = _this._getInternalFormat(format);
  12446. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12447. var needConversion = false;
  12448. if (internalFormat === gl.RGB) {
  12449. internalFormat = gl.RGBA;
  12450. needConversion = true;
  12451. }
  12452. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12453. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12454. var mipData = mipmmapGenerator(faceDataArrays);
  12455. for (var level = 0; level < mipData.length; level++) {
  12456. var mipSize = width >> level;
  12457. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12458. var mipFaceData = mipData[level][faceIndex];
  12459. if (needConversion) {
  12460. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12461. }
  12462. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12463. }
  12464. }
  12465. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12466. }
  12467. else {
  12468. texture.generateMipMaps = !noMipmap;
  12469. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12470. }
  12471. texture.isReady = true;
  12472. // this.resetTextureCache();
  12473. scene._removePendingData(texture);
  12474. if (onLoad) {
  12475. onLoad();
  12476. }
  12477. };
  12478. this._loadFile(url, function (data) {
  12479. internalCallback(data);
  12480. }, undefined, scene.database, true, onerror);
  12481. return texture;
  12482. };
  12483. ;
  12484. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  12485. if (compression === void 0) { compression = null; }
  12486. var internalFormat = this._getInternalFormat(format);
  12487. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12488. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12489. if (!this._doNotHandleContextLost) {
  12490. texture._bufferView = data;
  12491. texture.format = format;
  12492. texture.invertY = invertY;
  12493. texture._compression = compression;
  12494. }
  12495. if (texture.width % 4 !== 0) {
  12496. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12497. }
  12498. if (compression && data) {
  12499. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  12500. }
  12501. else {
  12502. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  12503. }
  12504. if (texture.generateMipMaps) {
  12505. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12506. }
  12507. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12508. // this.resetTextureCache();
  12509. texture.isReady = true;
  12510. };
  12511. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  12512. if (compression === void 0) { compression = null; }
  12513. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  12514. texture.baseWidth = width;
  12515. texture.baseHeight = height;
  12516. texture.baseDepth = depth;
  12517. texture.width = width;
  12518. texture.height = height;
  12519. texture.depth = depth;
  12520. texture.format = format;
  12521. texture.generateMipMaps = generateMipMaps;
  12522. texture.samplingMode = samplingMode;
  12523. texture.is3D = true;
  12524. if (!this._doNotHandleContextLost) {
  12525. texture._bufferView = data;
  12526. }
  12527. this.updateRawTexture3D(texture, data, format, invertY, compression);
  12528. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12529. // Filters
  12530. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12531. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12532. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12533. if (generateMipMaps) {
  12534. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12535. }
  12536. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12537. this._internalTexturesCache.push(texture);
  12538. return texture;
  12539. };
  12540. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  12541. var gl = this._gl;
  12542. if (!gl) {
  12543. return;
  12544. }
  12545. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  12546. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12547. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12548. if (!noMipmap && !isCompressed) {
  12549. gl.generateMipmap(gl.TEXTURE_2D);
  12550. }
  12551. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12552. // this.resetTextureCache();
  12553. if (scene) {
  12554. scene._removePendingData(texture);
  12555. }
  12556. texture.onLoadedObservable.notifyObservers(texture);
  12557. texture.onLoadedObservable.clear();
  12558. };
  12559. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  12560. var _this = this;
  12561. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12562. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  12563. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  12564. var gl = this._gl;
  12565. if (!gl) {
  12566. return;
  12567. }
  12568. if (!texture._webGLTexture) {
  12569. // this.resetTextureCache();
  12570. if (scene) {
  12571. scene._removePendingData(texture);
  12572. }
  12573. return;
  12574. }
  12575. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12576. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12577. texture.baseWidth = width;
  12578. texture.baseHeight = height;
  12579. texture.width = potWidth;
  12580. texture.height = potHeight;
  12581. texture.isReady = true;
  12582. if (processFunction(potWidth, potHeight, function () {
  12583. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12584. })) {
  12585. // Returning as texture needs extra async steps
  12586. return;
  12587. }
  12588. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12589. };
  12590. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  12591. // Create new RGBA data container.
  12592. var rgbaData;
  12593. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  12594. rgbaData = new Float32Array(width * height * 4);
  12595. }
  12596. else {
  12597. rgbaData = new Uint32Array(width * height * 4);
  12598. }
  12599. // Convert each pixel.
  12600. for (var x = 0; x < width; x++) {
  12601. for (var y = 0; y < height; y++) {
  12602. var index = (y * width + x) * 3;
  12603. var newIndex = (y * width + x) * 4;
  12604. // Map Old Value to new value.
  12605. rgbaData[newIndex + 0] = rgbData[index + 0];
  12606. rgbaData[newIndex + 1] = rgbData[index + 1];
  12607. rgbaData[newIndex + 2] = rgbData[index + 2];
  12608. // Add fully opaque alpha channel.
  12609. rgbaData[newIndex + 3] = 1;
  12610. }
  12611. }
  12612. return rgbaData;
  12613. };
  12614. Engine.prototype._releaseFramebufferObjects = function (texture) {
  12615. var gl = this._gl;
  12616. if (texture._framebuffer) {
  12617. gl.deleteFramebuffer(texture._framebuffer);
  12618. texture._framebuffer = null;
  12619. }
  12620. if (texture._depthStencilBuffer) {
  12621. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12622. texture._depthStencilBuffer = null;
  12623. }
  12624. if (texture._MSAAFramebuffer) {
  12625. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12626. texture._MSAAFramebuffer = null;
  12627. }
  12628. if (texture._MSAARenderBuffer) {
  12629. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12630. texture._MSAARenderBuffer = null;
  12631. }
  12632. };
  12633. Engine.prototype._releaseTexture = function (texture) {
  12634. var gl = this._gl;
  12635. this._releaseFramebufferObjects(texture);
  12636. gl.deleteTexture(texture._webGLTexture);
  12637. // Unbind channels
  12638. this.unbindAllTextures();
  12639. var index = this._internalTexturesCache.indexOf(texture);
  12640. if (index !== -1) {
  12641. this._internalTexturesCache.splice(index, 1);
  12642. }
  12643. // Integrated fixed lod samplers.
  12644. if (texture._lodTextureHigh) {
  12645. texture._lodTextureHigh.dispose();
  12646. }
  12647. if (texture._lodTextureMid) {
  12648. texture._lodTextureMid.dispose();
  12649. }
  12650. if (texture._lodTextureLow) {
  12651. texture._lodTextureLow.dispose();
  12652. }
  12653. };
  12654. Engine.prototype.setProgram = function (program) {
  12655. if (this._currentProgram !== program) {
  12656. this._gl.useProgram(program);
  12657. this._currentProgram = program;
  12658. }
  12659. };
  12660. Engine.prototype.bindSamplers = function (effect) {
  12661. this.setProgram(effect.getProgram());
  12662. var samplers = effect.getSamplers();
  12663. for (var index = 0; index < samplers.length; index++) {
  12664. var uniform = effect.getUniform(samplers[index]);
  12665. if (uniform) {
  12666. this._boundUniforms[index] = uniform;
  12667. }
  12668. }
  12669. this._currentEffect = null;
  12670. };
  12671. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  12672. var index = this._boundTexturesStack.indexOf(internalTexture);
  12673. if (index > -1 && index !== this._boundTexturesStack.length - 1) {
  12674. this._boundTexturesStack.splice(index, 1);
  12675. this._boundTexturesStack.push(internalTexture);
  12676. }
  12677. };
  12678. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  12679. if (!internalTexture) {
  12680. return -1;
  12681. }
  12682. internalTexture._initialSlot = channel;
  12683. if (this.disableTextureBindingOptimization) {
  12684. if (channel !== internalTexture._designatedSlot) {
  12685. this._textureCollisions.addCount(1, false);
  12686. }
  12687. }
  12688. else {
  12689. if (channel !== internalTexture._designatedSlot) {
  12690. if (internalTexture._designatedSlot > -1) {
  12691. return internalTexture._designatedSlot;
  12692. }
  12693. else {
  12694. // No slot for this texture, let's pick a new one (if we find a free slot)
  12695. if (this._nextFreeTextureSlots.length) {
  12696. return this._nextFreeTextureSlots[0];
  12697. }
  12698. // We need to recycle the oldest bound texture, sorry.
  12699. this._textureCollisions.addCount(1, false);
  12700. return this._removeDesignatedSlot(this._boundTexturesStack[0]);
  12701. }
  12702. }
  12703. }
  12704. return channel;
  12705. };
  12706. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  12707. var currentSlot = internalTexture._designatedSlot;
  12708. internalTexture._designatedSlot = -1;
  12709. var index = this._boundTexturesStack.indexOf(internalTexture);
  12710. if (index > -1) {
  12711. this._boundTexturesStack.splice(index, 1);
  12712. if (currentSlot > -1) {
  12713. this._boundTexturesCache[currentSlot] = null;
  12714. this._nextFreeTextureSlots.push(currentSlot);
  12715. }
  12716. }
  12717. return currentSlot;
  12718. };
  12719. Engine.prototype._activateCurrentTexture = function () {
  12720. if (this._currentTextureChannel !== this._activeChannel) {
  12721. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  12722. this._currentTextureChannel = this._activeChannel;
  12723. }
  12724. };
  12725. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  12726. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  12727. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  12728. this._activeChannel = texture._designatedSlot;
  12729. }
  12730. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  12731. var isTextureForRendering = texture && texture._initialSlot > -1;
  12732. if (currentTextureBound !== texture) {
  12733. if (currentTextureBound && !this.disableTextureBindingOptimization) {
  12734. this._removeDesignatedSlot(currentTextureBound);
  12735. }
  12736. this._activateCurrentTexture();
  12737. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  12738. this._boundTexturesCache[this._activeChannel] = texture;
  12739. if (texture) {
  12740. if (!this.disableTextureBindingOptimization) {
  12741. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  12742. if (slotIndex > -1) {
  12743. this._nextFreeTextureSlots.splice(slotIndex, 1);
  12744. }
  12745. this._boundTexturesStack.push(texture);
  12746. }
  12747. texture._designatedSlot = this._activeChannel;
  12748. }
  12749. }
  12750. else if (forTextureDataUpdate) {
  12751. this._activateCurrentTexture();
  12752. }
  12753. if (isTextureForRendering && !forTextureDataUpdate) {
  12754. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  12755. }
  12756. };
  12757. Engine.prototype._bindTexture = function (channel, texture) {
  12758. if (channel < 0) {
  12759. return;
  12760. }
  12761. if (texture) {
  12762. channel = this._getCorrectTextureChannel(channel, texture);
  12763. }
  12764. this._activeChannel = channel;
  12765. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  12766. };
  12767. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12768. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  12769. };
  12770. Engine.prototype.unbindAllTextures = function () {
  12771. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  12772. this._activeChannel = channel;
  12773. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12774. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12775. if (this.webGLVersion > 1) {
  12776. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12777. }
  12778. }
  12779. };
  12780. Engine.prototype.setTexture = function (channel, uniform, texture) {
  12781. if (channel < 0) {
  12782. return;
  12783. }
  12784. if (uniform) {
  12785. this._boundUniforms[channel] = uniform;
  12786. }
  12787. this._setTexture(channel, texture);
  12788. };
  12789. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  12790. var uniform = this._boundUniforms[sourceSlot];
  12791. if (uniform._currentState === destination) {
  12792. return;
  12793. }
  12794. this._gl.uniform1i(uniform, destination);
  12795. uniform._currentState = destination;
  12796. };
  12797. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  12798. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  12799. // Not ready?
  12800. if (!texture) {
  12801. if (this._boundTexturesCache[channel] != null) {
  12802. this._activeChannel = channel;
  12803. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12804. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12805. if (this.webGLVersion > 1) {
  12806. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12807. }
  12808. }
  12809. return false;
  12810. }
  12811. // Video
  12812. if (texture.video) {
  12813. this._activeChannel = channel;
  12814. texture.update();
  12815. }
  12816. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  12817. texture.delayLoad();
  12818. return false;
  12819. }
  12820. var internalTexture;
  12821. if (texture.isReady()) {
  12822. internalTexture = texture.getInternalTexture();
  12823. }
  12824. else if (texture.isCube) {
  12825. internalTexture = this.emptyCubeTexture;
  12826. }
  12827. else if (texture.is3D) {
  12828. internalTexture = this.emptyTexture3D;
  12829. }
  12830. else {
  12831. internalTexture = this.emptyTexture;
  12832. }
  12833. if (!isPartOfTextureArray) {
  12834. channel = this._getCorrectTextureChannel(channel, internalTexture);
  12835. }
  12836. if (this._boundTexturesCache[channel] === internalTexture) {
  12837. this._moveBoundTextureOnTop(internalTexture);
  12838. if (!isPartOfTextureArray) {
  12839. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  12840. }
  12841. return false;
  12842. }
  12843. this._activeChannel = channel;
  12844. if (internalTexture && internalTexture.is3D) {
  12845. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  12846. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12847. internalTexture._cachedWrapU = texture.wrapU;
  12848. switch (texture.wrapU) {
  12849. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12850. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12851. break;
  12852. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12853. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12854. break;
  12855. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12856. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12857. break;
  12858. }
  12859. }
  12860. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12861. internalTexture._cachedWrapV = texture.wrapV;
  12862. switch (texture.wrapV) {
  12863. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12864. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12865. break;
  12866. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12867. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12868. break;
  12869. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12870. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12871. break;
  12872. }
  12873. }
  12874. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  12875. internalTexture._cachedWrapR = texture.wrapR;
  12876. switch (texture.wrapV) {
  12877. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12878. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  12879. break;
  12880. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12881. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  12882. break;
  12883. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12884. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  12885. break;
  12886. }
  12887. }
  12888. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  12889. }
  12890. else if (internalTexture && internalTexture.isCube) {
  12891. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  12892. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  12893. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  12894. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  12895. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  12896. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  12897. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  12898. }
  12899. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  12900. }
  12901. else {
  12902. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  12903. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12904. internalTexture._cachedWrapU = texture.wrapU;
  12905. switch (texture.wrapU) {
  12906. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12907. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12908. break;
  12909. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12910. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12911. break;
  12912. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12913. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12914. break;
  12915. }
  12916. }
  12917. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12918. internalTexture._cachedWrapV = texture.wrapV;
  12919. switch (texture.wrapV) {
  12920. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12921. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12922. break;
  12923. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12924. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12925. break;
  12926. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12927. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12928. break;
  12929. }
  12930. }
  12931. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  12932. }
  12933. return true;
  12934. };
  12935. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  12936. if (channel < 0 || !uniform) {
  12937. return;
  12938. }
  12939. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  12940. this._textureUnits = new Int32Array(textures.length);
  12941. }
  12942. for (var i = 0; i < textures.length; i++) {
  12943. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  12944. }
  12945. this._gl.uniform1iv(uniform, this._textureUnits);
  12946. for (var index = 0; index < textures.length; index++) {
  12947. this._setTexture(this._textureUnits[index], textures[index], true);
  12948. }
  12949. };
  12950. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  12951. var internalTexture = texture.getInternalTexture();
  12952. if (!internalTexture) {
  12953. return;
  12954. }
  12955. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  12956. var value = texture.anisotropicFilteringLevel;
  12957. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  12958. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  12959. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  12960. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  12961. }
  12962. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  12963. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  12964. internalTexture._cachedAnisotropicFilteringLevel = value;
  12965. }
  12966. };
  12967. Engine.prototype.readPixels = function (x, y, width, height) {
  12968. var data = new Uint8Array(height * width * 4);
  12969. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  12970. return data;
  12971. };
  12972. /**
  12973. * Add an externaly attached data from its key.
  12974. * This method call will fail and return false, if such key already exists.
  12975. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  12976. * @param key the unique key that identifies the data
  12977. * @param data the data object to associate to the key for this Engine instance
  12978. * @return true if no such key were already present and the data was added successfully, false otherwise
  12979. */
  12980. Engine.prototype.addExternalData = function (key, data) {
  12981. if (!this._externalData) {
  12982. this._externalData = new BABYLON.StringDictionary();
  12983. }
  12984. return this._externalData.add(key, data);
  12985. };
  12986. /**
  12987. * Get an externaly attached data from its key
  12988. * @param key the unique key that identifies the data
  12989. * @return the associated data, if present (can be null), or undefined if not present
  12990. */
  12991. Engine.prototype.getExternalData = function (key) {
  12992. if (!this._externalData) {
  12993. this._externalData = new BABYLON.StringDictionary();
  12994. }
  12995. return this._externalData.get(key);
  12996. };
  12997. /**
  12998. * Get an externaly attached data from its key, create it using a factory if it's not already present
  12999. * @param key the unique key that identifies the data
  13000. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  13001. * @return the associated data, can be null if the factory returned null.
  13002. */
  13003. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  13004. if (!this._externalData) {
  13005. this._externalData = new BABYLON.StringDictionary();
  13006. }
  13007. return this._externalData.getOrAddWithFactory(key, factory);
  13008. };
  13009. /**
  13010. * Remove an externaly attached data from the Engine instance
  13011. * @param key the unique key that identifies the data
  13012. * @return true if the data was successfully removed, false if it doesn't exist
  13013. */
  13014. Engine.prototype.removeExternalData = function (key) {
  13015. if (!this._externalData) {
  13016. this._externalData = new BABYLON.StringDictionary();
  13017. }
  13018. return this._externalData.remove(key);
  13019. };
  13020. Engine.prototype.unbindAllAttributes = function () {
  13021. if (this._mustWipeVertexAttributes) {
  13022. this._mustWipeVertexAttributes = false;
  13023. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13024. this._gl.disableVertexAttribArray(i);
  13025. this._vertexAttribArraysEnabled[i] = false;
  13026. this._currentBufferPointers[i].active = false;
  13027. }
  13028. return;
  13029. }
  13030. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13031. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13032. continue;
  13033. }
  13034. this._gl.disableVertexAttribArray(i);
  13035. this._vertexAttribArraysEnabled[i] = false;
  13036. this._currentBufferPointers[i].active = false;
  13037. }
  13038. };
  13039. Engine.prototype.releaseEffects = function () {
  13040. for (var name in this._compiledEffects) {
  13041. this._deleteProgram(this._compiledEffects[name]._program);
  13042. }
  13043. this._compiledEffects = {};
  13044. };
  13045. // Dispose
  13046. Engine.prototype.dispose = function () {
  13047. this.hideLoadingUI();
  13048. this.stopRenderLoop();
  13049. // Release postProcesses
  13050. while (this.postProcesses.length) {
  13051. this.postProcesses[0].dispose();
  13052. }
  13053. // Empty texture
  13054. if (this._emptyTexture) {
  13055. this._releaseTexture(this._emptyTexture);
  13056. this._emptyTexture = null;
  13057. }
  13058. if (this._emptyCubeTexture) {
  13059. this._releaseTexture(this._emptyCubeTexture);
  13060. this._emptyCubeTexture = null;
  13061. }
  13062. // Rescale PP
  13063. if (this._rescalePostProcess) {
  13064. this._rescalePostProcess.dispose();
  13065. }
  13066. // Release scenes
  13067. while (this.scenes.length) {
  13068. this.scenes[0].dispose();
  13069. }
  13070. // Release audio engine
  13071. if (Engine.audioEngine) {
  13072. Engine.audioEngine.dispose();
  13073. }
  13074. // Release effects
  13075. this.releaseEffects();
  13076. // Unbind
  13077. this.unbindAllAttributes();
  13078. if (this._dummyFramebuffer) {
  13079. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13080. }
  13081. //WebVR
  13082. this.disableVR();
  13083. // Events
  13084. if (BABYLON.Tools.IsWindowObjectExist()) {
  13085. window.removeEventListener("blur", this._onBlur);
  13086. window.removeEventListener("focus", this._onFocus);
  13087. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13088. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13089. if (this._renderingCanvas) {
  13090. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13091. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13092. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13093. if (!this._doNotHandleContextLost) {
  13094. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13095. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13096. }
  13097. }
  13098. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13099. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13100. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13101. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13102. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13103. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13104. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13105. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13106. if (this._onVrDisplayConnect) {
  13107. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13108. if (this._onVrDisplayDisconnect) {
  13109. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13110. }
  13111. if (this._onVrDisplayPresentChange) {
  13112. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13113. }
  13114. this._onVrDisplayConnect = null;
  13115. this._onVrDisplayDisconnect = null;
  13116. }
  13117. }
  13118. // Remove from Instances
  13119. var index = Engine.Instances.indexOf(this);
  13120. if (index >= 0) {
  13121. delete Engine.Instances[index];
  13122. }
  13123. this._workingCanvas = null;
  13124. this._workingContext = null;
  13125. this._currentBufferPointers = [];
  13126. this._renderingCanvas = null;
  13127. this._currentProgram = null;
  13128. this.onResizeObservable.clear();
  13129. this.onCanvasBlurObservable.clear();
  13130. this.onCanvasFocusObservable.clear();
  13131. this.onCanvasPointerOutObservable.clear();
  13132. this.onBeginFrameObservable.clear();
  13133. this.onEndFrameObservable.clear();
  13134. BABYLON.Effect.ResetCache();
  13135. // Abort active requests
  13136. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13137. var request = _a[_i];
  13138. request.abort();
  13139. }
  13140. };
  13141. // Loading screen
  13142. Engine.prototype.displayLoadingUI = function () {
  13143. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13144. return;
  13145. }
  13146. var loadingScreen = this.loadingScreen;
  13147. if (loadingScreen) {
  13148. loadingScreen.displayLoadingUI();
  13149. }
  13150. };
  13151. Engine.prototype.hideLoadingUI = function () {
  13152. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13153. return;
  13154. }
  13155. var loadingScreen = this.loadingScreen;
  13156. if (loadingScreen) {
  13157. loadingScreen.hideLoadingUI();
  13158. }
  13159. };
  13160. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13161. get: function () {
  13162. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13163. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13164. return this._loadingScreen;
  13165. },
  13166. set: function (loadingScreen) {
  13167. this._loadingScreen = loadingScreen;
  13168. },
  13169. enumerable: true,
  13170. configurable: true
  13171. });
  13172. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13173. set: function (text) {
  13174. this.loadingScreen.loadingUIText = text;
  13175. },
  13176. enumerable: true,
  13177. configurable: true
  13178. });
  13179. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13180. set: function (color) {
  13181. this.loadingScreen.loadingUIBackgroundColor = color;
  13182. },
  13183. enumerable: true,
  13184. configurable: true
  13185. });
  13186. Engine.prototype.attachContextLostEvent = function (callback) {
  13187. if (this._renderingCanvas) {
  13188. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13189. }
  13190. };
  13191. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13192. if (this._renderingCanvas) {
  13193. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13194. }
  13195. };
  13196. Engine.prototype.getVertexShaderSource = function (program) {
  13197. var shaders = this._gl.getAttachedShaders(program);
  13198. if (!shaders) {
  13199. return null;
  13200. }
  13201. return this._gl.getShaderSource(shaders[0]);
  13202. };
  13203. Engine.prototype.getFragmentShaderSource = function (program) {
  13204. var shaders = this._gl.getAttachedShaders(program);
  13205. if (!shaders) {
  13206. return null;
  13207. }
  13208. return this._gl.getShaderSource(shaders[1]);
  13209. };
  13210. Engine.prototype.getError = function () {
  13211. return this._gl.getError();
  13212. };
  13213. // FPS
  13214. Engine.prototype.getFps = function () {
  13215. return this._fps;
  13216. };
  13217. Engine.prototype.getDeltaTime = function () {
  13218. return this._deltaTime;
  13219. };
  13220. Engine.prototype._measureFps = function () {
  13221. this._performanceMonitor.sampleFrame();
  13222. this._fps = this._performanceMonitor.averageFPS;
  13223. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13224. };
  13225. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13226. if (faceIndex === void 0) { faceIndex = -1; }
  13227. var gl = this._gl;
  13228. if (!this._dummyFramebuffer) {
  13229. var dummy = gl.createFramebuffer();
  13230. if (!dummy) {
  13231. throw new Error("Unable to create dummy framebuffer");
  13232. }
  13233. this._dummyFramebuffer = dummy;
  13234. }
  13235. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13236. if (faceIndex > -1) {
  13237. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13238. }
  13239. else {
  13240. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13241. }
  13242. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13243. var buffer;
  13244. switch (readType) {
  13245. case gl.UNSIGNED_BYTE:
  13246. buffer = new Uint8Array(4 * width * height);
  13247. readType = gl.UNSIGNED_BYTE;
  13248. break;
  13249. default:
  13250. buffer = new Float32Array(4 * width * height);
  13251. readType = gl.FLOAT;
  13252. break;
  13253. }
  13254. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13255. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13256. return buffer;
  13257. };
  13258. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13259. if (this._webGLVersion > 1) {
  13260. return this._caps.colorBufferFloat;
  13261. }
  13262. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13263. };
  13264. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13265. if (this._webGLVersion > 1) {
  13266. return this._caps.colorBufferFloat;
  13267. }
  13268. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13269. };
  13270. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13271. Engine.prototype._canRenderToFramebuffer = function (type) {
  13272. var gl = this._gl;
  13273. //clear existing errors
  13274. while (gl.getError() !== gl.NO_ERROR) { }
  13275. var successful = true;
  13276. var texture = gl.createTexture();
  13277. gl.bindTexture(gl.TEXTURE_2D, texture);
  13278. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13279. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13280. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13281. var fb = gl.createFramebuffer();
  13282. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13283. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13284. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13285. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13286. successful = successful && (gl.getError() === gl.NO_ERROR);
  13287. //try render by clearing frame buffer's color buffer
  13288. if (successful) {
  13289. gl.clear(gl.COLOR_BUFFER_BIT);
  13290. successful = successful && (gl.getError() === gl.NO_ERROR);
  13291. }
  13292. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13293. if (successful) {
  13294. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13295. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13296. var readFormat = gl.RGBA;
  13297. var readType = gl.UNSIGNED_BYTE;
  13298. var buffer = new Uint8Array(4);
  13299. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13300. successful = successful && (gl.getError() === gl.NO_ERROR);
  13301. }
  13302. //clean up
  13303. gl.deleteTexture(texture);
  13304. gl.deleteFramebuffer(fb);
  13305. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13306. //clear accumulated errors
  13307. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13308. return successful;
  13309. };
  13310. Engine.prototype._getWebGLTextureType = function (type) {
  13311. if (type === Engine.TEXTURETYPE_FLOAT) {
  13312. return this._gl.FLOAT;
  13313. }
  13314. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13315. // Add Half Float Constant.
  13316. return this._gl.HALF_FLOAT_OES;
  13317. }
  13318. return this._gl.UNSIGNED_BYTE;
  13319. };
  13320. ;
  13321. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13322. if (this._webGLVersion === 1) {
  13323. return this._gl.RGBA;
  13324. }
  13325. if (type === Engine.TEXTURETYPE_FLOAT) {
  13326. return this._gl.RGBA32F;
  13327. }
  13328. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13329. return this._gl.RGBA16F;
  13330. }
  13331. return this._gl.RGBA;
  13332. };
  13333. ;
  13334. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13335. if (type === Engine.TEXTURETYPE_FLOAT) {
  13336. return this._gl.RGBA32F;
  13337. }
  13338. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13339. return this._gl.RGBA16F;
  13340. }
  13341. return this._gl.RGBA8;
  13342. };
  13343. ;
  13344. Engine.prototype.createQuery = function () {
  13345. return this._gl.createQuery();
  13346. };
  13347. Engine.prototype.deleteQuery = function (query) {
  13348. this._gl.deleteQuery(query);
  13349. return this;
  13350. };
  13351. Engine.prototype.isQueryResultAvailable = function (query) {
  13352. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13353. };
  13354. Engine.prototype.getQueryResult = function (query) {
  13355. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13356. };
  13357. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13358. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13359. this._gl.beginQuery(glAlgorithm, query);
  13360. return this;
  13361. };
  13362. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13363. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13364. this._gl.endQuery(glAlgorithm);
  13365. return this;
  13366. };
  13367. /* Time queries */
  13368. Engine.prototype._createTimeQuery = function () {
  13369. var timerQuery = this._caps.timerQuery;
  13370. if (timerQuery.createQueryEXT) {
  13371. return timerQuery.createQueryEXT();
  13372. }
  13373. return this.createQuery();
  13374. };
  13375. Engine.prototype._deleteTimeQuery = function (query) {
  13376. var timerQuery = this._caps.timerQuery;
  13377. if (timerQuery.deleteQueryEXT) {
  13378. timerQuery.deleteQueryEXT(query);
  13379. return;
  13380. }
  13381. this.deleteQuery(query);
  13382. };
  13383. Engine.prototype._getTimeQueryResult = function (query) {
  13384. var timerQuery = this._caps.timerQuery;
  13385. if (timerQuery.getQueryObjectEXT) {
  13386. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13387. }
  13388. return this.getQueryResult(query);
  13389. };
  13390. Engine.prototype._getTimeQueryAvailability = function (query) {
  13391. var timerQuery = this._caps.timerQuery;
  13392. if (timerQuery.getQueryObjectEXT) {
  13393. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13394. }
  13395. return this.isQueryResultAvailable(query);
  13396. };
  13397. Engine.prototype.startTimeQuery = function () {
  13398. var timerQuery = this._caps.timerQuery;
  13399. if (!timerQuery) {
  13400. return null;
  13401. }
  13402. var token = new BABYLON._TimeToken();
  13403. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13404. if (this._caps.canUseTimestampForTimerQuery) {
  13405. token._startTimeQuery = this._createTimeQuery();
  13406. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13407. }
  13408. else {
  13409. if (this._currentNonTimestampToken) {
  13410. return this._currentNonTimestampToken;
  13411. }
  13412. token._timeElapsedQuery = this._createTimeQuery();
  13413. if (timerQuery.beginQueryEXT) {
  13414. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13415. }
  13416. else {
  13417. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13418. }
  13419. this._currentNonTimestampToken = token;
  13420. }
  13421. return token;
  13422. };
  13423. Engine.prototype.endTimeQuery = function (token) {
  13424. var timerQuery = this._caps.timerQuery;
  13425. if (!timerQuery || !token) {
  13426. return -1;
  13427. }
  13428. if (this._caps.canUseTimestampForTimerQuery) {
  13429. if (!token._startTimeQuery) {
  13430. return -1;
  13431. }
  13432. if (!token._endTimeQuery) {
  13433. token._endTimeQuery = this._createTimeQuery();
  13434. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13435. }
  13436. }
  13437. else if (!token._timeElapsedQueryEnded) {
  13438. if (!token._timeElapsedQuery) {
  13439. return -1;
  13440. }
  13441. if (timerQuery.endQueryEXT) {
  13442. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13443. }
  13444. else {
  13445. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13446. }
  13447. token._timeElapsedQueryEnded = true;
  13448. }
  13449. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13450. var available = false;
  13451. if (token._endTimeQuery) {
  13452. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13453. }
  13454. else if (token._timeElapsedQuery) {
  13455. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13456. }
  13457. if (available && !disjoint) {
  13458. var result = 0;
  13459. if (this._caps.canUseTimestampForTimerQuery) {
  13460. if (!token._startTimeQuery || !token._endTimeQuery) {
  13461. return -1;
  13462. }
  13463. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  13464. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  13465. result = timeEnd - timeStart;
  13466. this._deleteTimeQuery(token._startTimeQuery);
  13467. this._deleteTimeQuery(token._endTimeQuery);
  13468. token._startTimeQuery = null;
  13469. token._endTimeQuery = null;
  13470. }
  13471. else {
  13472. if (!token._timeElapsedQuery) {
  13473. return -1;
  13474. }
  13475. result = this._getTimeQueryResult(token._timeElapsedQuery);
  13476. this._deleteTimeQuery(token._timeElapsedQuery);
  13477. token._timeElapsedQuery = null;
  13478. token._timeElapsedQueryEnded = false;
  13479. this._currentNonTimestampToken = null;
  13480. }
  13481. return result;
  13482. }
  13483. return -1;
  13484. };
  13485. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  13486. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  13487. };
  13488. // Transform feedback
  13489. Engine.prototype.createTransformFeedback = function () {
  13490. return this._gl.createTransformFeedback();
  13491. };
  13492. Engine.prototype.deleteTransformFeedback = function (value) {
  13493. this._gl.deleteTransformFeedback(value);
  13494. };
  13495. Engine.prototype.bindTransformFeedback = function (value) {
  13496. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  13497. };
  13498. Engine.prototype.beginTransformFeedback = function (usePoints) {
  13499. if (usePoints === void 0) { usePoints = true; }
  13500. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  13501. };
  13502. Engine.prototype.endTransformFeedback = function () {
  13503. this._gl.endTransformFeedback();
  13504. };
  13505. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  13506. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  13507. };
  13508. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  13509. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  13510. };
  13511. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  13512. var _this = this;
  13513. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  13514. this._activeRequests.push(request);
  13515. request.onCompleteObservable.add(function (request) {
  13516. delete _this._activeRequests[_this._activeRequests.indexOf(request)];
  13517. });
  13518. return request;
  13519. };
  13520. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  13521. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  13522. var onload = function (data) {
  13523. loadedFiles[index] = data;
  13524. loadedFiles._internalCount++;
  13525. if (loadedFiles._internalCount === 6) {
  13526. onfinish(loadedFiles);
  13527. }
  13528. };
  13529. var onerror = function (request, exception) {
  13530. if (onErrorCallBack && request) {
  13531. onErrorCallBack(request.status + " " + request.statusText, exception);
  13532. }
  13533. };
  13534. this._loadFile(url, onload, undefined, undefined, true, onerror);
  13535. };
  13536. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  13537. if (onError === void 0) { onError = null; }
  13538. var loadedFiles = [];
  13539. loadedFiles._internalCount = 0;
  13540. for (var index = 0; index < 6; index++) {
  13541. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  13542. }
  13543. };
  13544. // Statics
  13545. Engine.isSupported = function () {
  13546. try {
  13547. var tempcanvas = document.createElement("canvas");
  13548. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  13549. return gl != null && !!window.WebGLRenderingContext;
  13550. }
  13551. catch (e) {
  13552. return false;
  13553. }
  13554. };
  13555. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  13556. Engine.ExceptionList = [
  13557. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  13558. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  13559. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  13560. ];
  13561. Engine.Instances = new Array();
  13562. // Const statics
  13563. Engine._ALPHA_DISABLE = 0;
  13564. Engine._ALPHA_ADD = 1;
  13565. Engine._ALPHA_COMBINE = 2;
  13566. Engine._ALPHA_SUBTRACT = 3;
  13567. Engine._ALPHA_MULTIPLY = 4;
  13568. Engine._ALPHA_MAXIMIZED = 5;
  13569. Engine._ALPHA_ONEONE = 6;
  13570. Engine._ALPHA_PREMULTIPLIED = 7;
  13571. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  13572. Engine._ALPHA_INTERPOLATE = 9;
  13573. Engine._ALPHA_SCREENMODE = 10;
  13574. Engine._DELAYLOADSTATE_NONE = 0;
  13575. Engine._DELAYLOADSTATE_LOADED = 1;
  13576. Engine._DELAYLOADSTATE_LOADING = 2;
  13577. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  13578. Engine._TEXTUREFORMAT_ALPHA = 0;
  13579. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  13580. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  13581. Engine._TEXTUREFORMAT_RGB = 4;
  13582. Engine._TEXTUREFORMAT_RGBA = 5;
  13583. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  13584. Engine._TEXTURETYPE_FLOAT = 1;
  13585. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  13586. // Depht or Stencil test Constants.
  13587. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  13588. 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.
  13589. 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.
  13590. 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.
  13591. 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.
  13592. 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.
  13593. 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.
  13594. 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.
  13595. // Stencil Actions Constants.
  13596. Engine._KEEP = 0x1E00;
  13597. Engine._REPLACE = 0x1E01;
  13598. Engine._INCR = 0x1E02;
  13599. Engine._DECR = 0x1E03;
  13600. Engine._INVERT = 0x150A;
  13601. Engine._INCR_WRAP = 0x8507;
  13602. Engine._DECR_WRAP = 0x8508;
  13603. // Texture rescaling mode
  13604. Engine._SCALEMODE_FLOOR = 1;
  13605. Engine._SCALEMODE_NEAREST = 2;
  13606. Engine._SCALEMODE_CEILING = 3;
  13607. // Updatable statics so stick with vars here
  13608. Engine.CollisionsEpsilon = 0.001;
  13609. Engine.CodeRepository = "src/";
  13610. Engine.ShadersRepository = "src/Shaders/";
  13611. return Engine;
  13612. }());
  13613. BABYLON.Engine = Engine;
  13614. })(BABYLON || (BABYLON = {}));
  13615. //# sourceMappingURL=babylon.engine.js.map
  13616. var BABYLON;
  13617. (function (BABYLON) {
  13618. /**
  13619. * Node is the basic class for all scene objects (Mesh, Light Camera).
  13620. */
  13621. var Node = /** @class */ (function () {
  13622. /**
  13623. * @constructor
  13624. * @param {string} name - the name and id to be given to this node
  13625. * @param {BABYLON.Scene} the scene this node will be added to
  13626. */
  13627. function Node(name, scene) {
  13628. if (scene === void 0) { scene = null; }
  13629. this.state = "";
  13630. this.metadata = null;
  13631. this.doNotSerialize = false;
  13632. this.animations = new Array();
  13633. this._ranges = {};
  13634. this._isEnabled = true;
  13635. this._isReady = true;
  13636. this._currentRenderId = -1;
  13637. this._parentRenderId = -1;
  13638. /**
  13639. * An event triggered when the mesh is disposed.
  13640. * @type {BABYLON.Observable}
  13641. */
  13642. this.onDisposeObservable = new BABYLON.Observable();
  13643. // Behaviors
  13644. this._behaviors = new Array();
  13645. this.name = name;
  13646. this.id = name;
  13647. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  13648. this.uniqueId = this._scene.getUniqueId();
  13649. this._initCache();
  13650. }
  13651. Object.defineProperty(Node.prototype, "parent", {
  13652. get: function () {
  13653. return this._parentNode;
  13654. },
  13655. set: function (parent) {
  13656. if (this._parentNode === parent) {
  13657. return;
  13658. }
  13659. // Remove self from list of children of parent
  13660. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  13661. var index = this._parentNode._children.indexOf(this);
  13662. if (index !== -1) {
  13663. this._parentNode._children.splice(index, 1);
  13664. }
  13665. }
  13666. // Store new parent
  13667. this._parentNode = parent;
  13668. // Add as child to new parent
  13669. if (this._parentNode) {
  13670. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  13671. this._parentNode._children = new Array();
  13672. }
  13673. this._parentNode._children.push(this);
  13674. }
  13675. },
  13676. enumerable: true,
  13677. configurable: true
  13678. });
  13679. Node.prototype.getClassName = function () {
  13680. return "Node";
  13681. };
  13682. Object.defineProperty(Node.prototype, "onDispose", {
  13683. set: function (callback) {
  13684. if (this._onDisposeObserver) {
  13685. this.onDisposeObservable.remove(this._onDisposeObserver);
  13686. }
  13687. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  13688. },
  13689. enumerable: true,
  13690. configurable: true
  13691. });
  13692. Node.prototype.getScene = function () {
  13693. return this._scene;
  13694. };
  13695. Node.prototype.getEngine = function () {
  13696. return this._scene.getEngine();
  13697. };
  13698. Node.prototype.addBehavior = function (behavior) {
  13699. var _this = this;
  13700. var index = this._behaviors.indexOf(behavior);
  13701. if (index !== -1) {
  13702. return this;
  13703. }
  13704. behavior.init();
  13705. if (this._scene.isLoading) {
  13706. // We defer the attach when the scene will be loaded
  13707. var observer = this._scene.onDataLoadedObservable.add(function () {
  13708. behavior.attach(_this);
  13709. setTimeout(function () {
  13710. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  13711. _this._scene.onDataLoadedObservable.remove(observer);
  13712. }, 0);
  13713. });
  13714. }
  13715. else {
  13716. behavior.attach(this);
  13717. }
  13718. this._behaviors.push(behavior);
  13719. return this;
  13720. };
  13721. Node.prototype.removeBehavior = function (behavior) {
  13722. var index = this._behaviors.indexOf(behavior);
  13723. if (index === -1) {
  13724. return this;
  13725. }
  13726. this._behaviors[index].detach();
  13727. this._behaviors.splice(index, 1);
  13728. return this;
  13729. };
  13730. Object.defineProperty(Node.prototype, "behaviors", {
  13731. get: function () {
  13732. return this._behaviors;
  13733. },
  13734. enumerable: true,
  13735. configurable: true
  13736. });
  13737. Node.prototype.getBehaviorByName = function (name) {
  13738. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13739. var behavior = _a[_i];
  13740. if (behavior.name === name) {
  13741. return behavior;
  13742. }
  13743. }
  13744. return null;
  13745. };
  13746. // override it in derived class
  13747. Node.prototype.getWorldMatrix = function () {
  13748. return BABYLON.Matrix.Identity();
  13749. };
  13750. // override it in derived class if you add new variables to the cache
  13751. // and call the parent class method
  13752. Node.prototype._initCache = function () {
  13753. this._cache = {};
  13754. this._cache.parent = undefined;
  13755. };
  13756. Node.prototype.updateCache = function (force) {
  13757. if (!force && this.isSynchronized())
  13758. return;
  13759. this._cache.parent = this.parent;
  13760. this._updateCache();
  13761. };
  13762. // override it in derived class if you add new variables to the cache
  13763. // and call the parent class method if !ignoreParentClass
  13764. Node.prototype._updateCache = function (ignoreParentClass) {
  13765. };
  13766. // override it in derived class if you add new variables to the cache
  13767. Node.prototype._isSynchronized = function () {
  13768. return true;
  13769. };
  13770. Node.prototype._markSyncedWithParent = function () {
  13771. if (this.parent) {
  13772. this._parentRenderId = this.parent._currentRenderId;
  13773. }
  13774. };
  13775. Node.prototype.isSynchronizedWithParent = function () {
  13776. if (!this.parent) {
  13777. return true;
  13778. }
  13779. if (this._parentRenderId !== this.parent._currentRenderId) {
  13780. return false;
  13781. }
  13782. return this.parent.isSynchronized();
  13783. };
  13784. Node.prototype.isSynchronized = function (updateCache) {
  13785. var check = this.hasNewParent();
  13786. check = check || !this.isSynchronizedWithParent();
  13787. check = check || !this._isSynchronized();
  13788. if (updateCache)
  13789. this.updateCache(true);
  13790. return !check;
  13791. };
  13792. Node.prototype.hasNewParent = function (update) {
  13793. if (this._cache.parent === this.parent)
  13794. return false;
  13795. if (update)
  13796. this._cache.parent = this.parent;
  13797. return true;
  13798. };
  13799. /**
  13800. * Is this node ready to be used/rendered
  13801. * @return {boolean} is it ready
  13802. */
  13803. Node.prototype.isReady = function () {
  13804. return this._isReady;
  13805. };
  13806. /**
  13807. * Is this node enabled.
  13808. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true.
  13809. * @param {boolean} [checkAncestors=true] - Indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors.
  13810. * @return {boolean} whether this node (and its parent) is enabled.
  13811. * @see setEnabled
  13812. */
  13813. Node.prototype.isEnabled = function (checkAncestors) {
  13814. if (checkAncestors === void 0) { checkAncestors = true; }
  13815. if (checkAncestors === false) {
  13816. return this._isEnabled;
  13817. }
  13818. if (this._isEnabled === false) {
  13819. return false;
  13820. }
  13821. if (this.parent !== undefined && this.parent !== null) {
  13822. return this.parent.isEnabled(checkAncestors);
  13823. }
  13824. return true;
  13825. };
  13826. /**
  13827. * Set the enabled state of this node.
  13828. * @param {boolean} value - the new enabled state
  13829. * @see isEnabled
  13830. */
  13831. Node.prototype.setEnabled = function (value) {
  13832. this._isEnabled = value;
  13833. };
  13834. /**
  13835. * Is this node a descendant of the given node.
  13836. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  13837. * @param {BABYLON.Node} ancestor - The parent node to inspect
  13838. * @see parent
  13839. */
  13840. Node.prototype.isDescendantOf = function (ancestor) {
  13841. if (this.parent) {
  13842. if (this.parent === ancestor) {
  13843. return true;
  13844. }
  13845. return this.parent.isDescendantOf(ancestor);
  13846. }
  13847. return false;
  13848. };
  13849. /**
  13850. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  13851. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  13852. * @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.
  13853. * @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.
  13854. */
  13855. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  13856. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  13857. if (!this._children) {
  13858. return;
  13859. }
  13860. for (var index = 0; index < this._children.length; index++) {
  13861. var item = this._children[index];
  13862. if (!predicate || predicate(item)) {
  13863. results.push(item);
  13864. }
  13865. if (!directDescendantsOnly) {
  13866. item._getDescendants(results, false, predicate);
  13867. }
  13868. }
  13869. };
  13870. /**
  13871. * Will return all nodes that have this node as ascendant.
  13872. * @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.
  13873. * @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.
  13874. * @return {BABYLON.Node[]} all children nodes of all types.
  13875. */
  13876. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  13877. var results = new Array();
  13878. this._getDescendants(results, directDescendantsOnly, predicate);
  13879. return results;
  13880. };
  13881. /**
  13882. * Get all child-meshes of this node.
  13883. */
  13884. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  13885. var results = [];
  13886. this._getDescendants(results, directDescendantsOnly, function (node) {
  13887. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  13888. });
  13889. return results;
  13890. };
  13891. /**
  13892. * Get all child-transformNodes of this node.
  13893. */
  13894. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  13895. var results = [];
  13896. this._getDescendants(results, directDescendantsOnly, function (node) {
  13897. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  13898. });
  13899. return results;
  13900. };
  13901. /**
  13902. * Get all direct children of this node.
  13903. */
  13904. Node.prototype.getChildren = function (predicate) {
  13905. return this.getDescendants(true, predicate);
  13906. };
  13907. Node.prototype._setReady = function (state) {
  13908. if (state === this._isReady) {
  13909. return;
  13910. }
  13911. if (!state) {
  13912. this._isReady = false;
  13913. return;
  13914. }
  13915. this._isReady = true;
  13916. if (this.onReady) {
  13917. this.onReady(this);
  13918. }
  13919. };
  13920. Node.prototype.getAnimationByName = function (name) {
  13921. for (var i = 0; i < this.animations.length; i++) {
  13922. var animation = this.animations[i];
  13923. if (animation.name === name) {
  13924. return animation;
  13925. }
  13926. }
  13927. return null;
  13928. };
  13929. Node.prototype.createAnimationRange = function (name, from, to) {
  13930. // check name not already in use
  13931. if (!this._ranges[name]) {
  13932. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  13933. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13934. if (this.animations[i]) {
  13935. this.animations[i].createRange(name, from, to);
  13936. }
  13937. }
  13938. }
  13939. };
  13940. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  13941. if (deleteFrames === void 0) { deleteFrames = true; }
  13942. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13943. if (this.animations[i]) {
  13944. this.animations[i].deleteRange(name, deleteFrames);
  13945. }
  13946. }
  13947. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  13948. };
  13949. Node.prototype.getAnimationRange = function (name) {
  13950. return this._ranges[name];
  13951. };
  13952. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  13953. var range = this.getAnimationRange(name);
  13954. if (!range) {
  13955. return;
  13956. }
  13957. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  13958. };
  13959. Node.prototype.serializeAnimationRanges = function () {
  13960. var serializationRanges = [];
  13961. for (var name in this._ranges) {
  13962. var localRange = this._ranges[name];
  13963. if (!localRange) {
  13964. continue;
  13965. }
  13966. var range = {};
  13967. range.name = name;
  13968. range.from = localRange.from;
  13969. range.to = localRange.to;
  13970. serializationRanges.push(range);
  13971. }
  13972. return serializationRanges;
  13973. };
  13974. // override it in derived class
  13975. Node.prototype.computeWorldMatrix = function (force) {
  13976. return BABYLON.Matrix.Identity();
  13977. };
  13978. Node.prototype.dispose = function () {
  13979. this.parent = null;
  13980. // Callback
  13981. this.onDisposeObservable.notifyObservers(this);
  13982. this.onDisposeObservable.clear();
  13983. // Behaviors
  13984. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13985. var behavior = _a[_i];
  13986. behavior.detach();
  13987. }
  13988. this._behaviors = [];
  13989. };
  13990. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  13991. if (parsedNode.ranges) {
  13992. for (var index = 0; index < parsedNode.ranges.length; index++) {
  13993. var data = parsedNode.ranges[index];
  13994. node.createAnimationRange(data.name, data.from, data.to);
  13995. }
  13996. }
  13997. };
  13998. __decorate([
  13999. BABYLON.serialize()
  14000. ], Node.prototype, "name", void 0);
  14001. __decorate([
  14002. BABYLON.serialize()
  14003. ], Node.prototype, "id", void 0);
  14004. __decorate([
  14005. BABYLON.serialize()
  14006. ], Node.prototype, "uniqueId", void 0);
  14007. __decorate([
  14008. BABYLON.serialize()
  14009. ], Node.prototype, "state", void 0);
  14010. __decorate([
  14011. BABYLON.serialize()
  14012. ], Node.prototype, "metadata", void 0);
  14013. return Node;
  14014. }());
  14015. BABYLON.Node = Node;
  14016. })(BABYLON || (BABYLON = {}));
  14017. //# sourceMappingURL=babylon.node.js.map
  14018. var BABYLON;
  14019. (function (BABYLON) {
  14020. var BoundingSphere = /** @class */ (function () {
  14021. function BoundingSphere(minimum, maximum) {
  14022. this.minimum = minimum;
  14023. this.maximum = maximum;
  14024. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14025. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14026. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14027. this.radius = distance * 0.5;
  14028. this.centerWorld = BABYLON.Vector3.Zero();
  14029. this._update(BABYLON.Matrix.Identity());
  14030. }
  14031. // Methods
  14032. BoundingSphere.prototype._update = function (world) {
  14033. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14034. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14035. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14036. };
  14037. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14038. for (var i = 0; i < 6; i++) {
  14039. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14040. return false;
  14041. }
  14042. return true;
  14043. };
  14044. BoundingSphere.prototype.intersectsPoint = function (point) {
  14045. var x = this.centerWorld.x - point.x;
  14046. var y = this.centerWorld.y - point.y;
  14047. var z = this.centerWorld.z - point.z;
  14048. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14049. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14050. return false;
  14051. return true;
  14052. };
  14053. // Statics
  14054. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14055. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14056. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14057. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14058. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14059. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14060. return false;
  14061. return true;
  14062. };
  14063. return BoundingSphere;
  14064. }());
  14065. BABYLON.BoundingSphere = BoundingSphere;
  14066. })(BABYLON || (BABYLON = {}));
  14067. //# sourceMappingURL=babylon.boundingSphere.js.map
  14068. var BABYLON;
  14069. (function (BABYLON) {
  14070. var BoundingBox = /** @class */ (function () {
  14071. function BoundingBox(minimum, maximum) {
  14072. this.minimum = minimum;
  14073. this.maximum = maximum;
  14074. this.vectors = new Array();
  14075. this.vectorsWorld = new Array();
  14076. // Bounding vectors
  14077. this.vectors.push(this.minimum.clone());
  14078. this.vectors.push(this.maximum.clone());
  14079. this.vectors.push(this.minimum.clone());
  14080. this.vectors[2].x = this.maximum.x;
  14081. this.vectors.push(this.minimum.clone());
  14082. this.vectors[3].y = this.maximum.y;
  14083. this.vectors.push(this.minimum.clone());
  14084. this.vectors[4].z = this.maximum.z;
  14085. this.vectors.push(this.maximum.clone());
  14086. this.vectors[5].z = this.minimum.z;
  14087. this.vectors.push(this.maximum.clone());
  14088. this.vectors[6].x = this.minimum.x;
  14089. this.vectors.push(this.maximum.clone());
  14090. this.vectors[7].y = this.minimum.y;
  14091. // OBB
  14092. this.center = this.maximum.add(this.minimum).scale(0.5);
  14093. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14094. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14095. // World
  14096. for (var index = 0; index < this.vectors.length; index++) {
  14097. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14098. }
  14099. this.minimumWorld = BABYLON.Vector3.Zero();
  14100. this.maximumWorld = BABYLON.Vector3.Zero();
  14101. this.centerWorld = BABYLON.Vector3.Zero();
  14102. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14103. this._update(BABYLON.Matrix.Identity());
  14104. }
  14105. // Methods
  14106. BoundingBox.prototype.getWorldMatrix = function () {
  14107. return this._worldMatrix;
  14108. };
  14109. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14110. this._worldMatrix.copyFrom(matrix);
  14111. return this;
  14112. };
  14113. BoundingBox.prototype._update = function (world) {
  14114. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14115. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14116. for (var index = 0; index < this.vectors.length; index++) {
  14117. var v = this.vectorsWorld[index];
  14118. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14119. if (v.x < this.minimumWorld.x)
  14120. this.minimumWorld.x = v.x;
  14121. if (v.y < this.minimumWorld.y)
  14122. this.minimumWorld.y = v.y;
  14123. if (v.z < this.minimumWorld.z)
  14124. this.minimumWorld.z = v.z;
  14125. if (v.x > this.maximumWorld.x)
  14126. this.maximumWorld.x = v.x;
  14127. if (v.y > this.maximumWorld.y)
  14128. this.maximumWorld.y = v.y;
  14129. if (v.z > this.maximumWorld.z)
  14130. this.maximumWorld.z = v.z;
  14131. }
  14132. // Extend
  14133. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14134. this.extendSizeWorld.scaleInPlace(0.5);
  14135. // OBB
  14136. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14137. this.centerWorld.scaleInPlace(0.5);
  14138. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14139. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14140. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14141. this._worldMatrix = world;
  14142. };
  14143. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14144. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14145. };
  14146. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14147. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14148. };
  14149. BoundingBox.prototype.intersectsPoint = function (point) {
  14150. var delta = -BABYLON.Epsilon;
  14151. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14152. return false;
  14153. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14154. return false;
  14155. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14156. return false;
  14157. return true;
  14158. };
  14159. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14160. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14161. };
  14162. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14163. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14164. return false;
  14165. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14166. return false;
  14167. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14168. return false;
  14169. return true;
  14170. };
  14171. // Statics
  14172. BoundingBox.Intersects = function (box0, box1) {
  14173. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14174. return false;
  14175. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14176. return false;
  14177. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14178. return false;
  14179. return true;
  14180. };
  14181. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14182. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14183. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14184. return (num <= (sphereRadius * sphereRadius));
  14185. };
  14186. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14187. for (var p = 0; p < 6; p++) {
  14188. for (var i = 0; i < 8; i++) {
  14189. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14190. return false;
  14191. }
  14192. }
  14193. }
  14194. return true;
  14195. };
  14196. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14197. for (var p = 0; p < 6; p++) {
  14198. var inCount = 8;
  14199. for (var i = 0; i < 8; i++) {
  14200. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14201. --inCount;
  14202. }
  14203. else {
  14204. break;
  14205. }
  14206. }
  14207. if (inCount === 0)
  14208. return false;
  14209. }
  14210. return true;
  14211. };
  14212. return BoundingBox;
  14213. }());
  14214. BABYLON.BoundingBox = BoundingBox;
  14215. })(BABYLON || (BABYLON = {}));
  14216. //# sourceMappingURL=babylon.boundingBox.js.map
  14217. var BABYLON;
  14218. (function (BABYLON) {
  14219. var computeBoxExtents = function (axis, box) {
  14220. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14221. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14222. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14223. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14224. var r = r0 + r1 + r2;
  14225. return {
  14226. min: p - r,
  14227. max: p + r
  14228. };
  14229. };
  14230. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14231. var axisOverlap = function (axis, box0, box1) {
  14232. var result0 = computeBoxExtents(axis, box0);
  14233. var result1 = computeBoxExtents(axis, box1);
  14234. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14235. };
  14236. var BoundingInfo = /** @class */ (function () {
  14237. function BoundingInfo(minimum, maximum) {
  14238. this.minimum = minimum;
  14239. this.maximum = maximum;
  14240. this._isLocked = false;
  14241. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14242. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14243. }
  14244. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14245. get: function () {
  14246. return this._isLocked;
  14247. },
  14248. set: function (value) {
  14249. this._isLocked = value;
  14250. },
  14251. enumerable: true,
  14252. configurable: true
  14253. });
  14254. // Methods
  14255. BoundingInfo.prototype.update = function (world) {
  14256. if (this._isLocked) {
  14257. return;
  14258. }
  14259. this.boundingBox._update(world);
  14260. this.boundingSphere._update(world);
  14261. };
  14262. /**
  14263. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14264. * @param center New center of the bounding info
  14265. * @param extend New extend of the bounding info
  14266. */
  14267. BoundingInfo.prototype.centerOn = function (center, extend) {
  14268. this.minimum = center.subtract(extend);
  14269. this.maximum = center.add(extend);
  14270. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14271. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14272. return this;
  14273. };
  14274. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14275. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14276. return false;
  14277. return this.boundingBox.isInFrustum(frustumPlanes);
  14278. };
  14279. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14280. /**
  14281. * Gets the world distance between the min and max points of the bounding box
  14282. */
  14283. get: function () {
  14284. var boundingBox = this.boundingBox;
  14285. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14286. return size.length();
  14287. },
  14288. enumerable: true,
  14289. configurable: true
  14290. });
  14291. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14292. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14293. };
  14294. BoundingInfo.prototype._checkCollision = function (collider) {
  14295. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14296. };
  14297. BoundingInfo.prototype.intersectsPoint = function (point) {
  14298. if (!this.boundingSphere.centerWorld) {
  14299. return false;
  14300. }
  14301. if (!this.boundingSphere.intersectsPoint(point)) {
  14302. return false;
  14303. }
  14304. if (!this.boundingBox.intersectsPoint(point)) {
  14305. return false;
  14306. }
  14307. return true;
  14308. };
  14309. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14310. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14311. return false;
  14312. }
  14313. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14314. return false;
  14315. }
  14316. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14317. return false;
  14318. }
  14319. if (!precise) {
  14320. return true;
  14321. }
  14322. var box0 = this.boundingBox;
  14323. var box1 = boundingInfo.boundingBox;
  14324. if (!axisOverlap(box0.directions[0], box0, box1))
  14325. return false;
  14326. if (!axisOverlap(box0.directions[1], box0, box1))
  14327. return false;
  14328. if (!axisOverlap(box0.directions[2], box0, box1))
  14329. return false;
  14330. if (!axisOverlap(box1.directions[0], box0, box1))
  14331. return false;
  14332. if (!axisOverlap(box1.directions[1], box0, box1))
  14333. return false;
  14334. if (!axisOverlap(box1.directions[2], box0, box1))
  14335. return false;
  14336. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14337. return false;
  14338. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14339. return false;
  14340. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14341. return false;
  14342. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14343. return false;
  14344. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14345. return false;
  14346. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14347. return false;
  14348. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14349. return false;
  14350. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14351. return false;
  14352. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14353. return false;
  14354. return true;
  14355. };
  14356. return BoundingInfo;
  14357. }());
  14358. BABYLON.BoundingInfo = BoundingInfo;
  14359. })(BABYLON || (BABYLON = {}));
  14360. //# sourceMappingURL=babylon.boundingInfo.js.map
  14361. var BABYLON;
  14362. (function (BABYLON) {
  14363. var TransformNode = /** @class */ (function (_super) {
  14364. __extends(TransformNode, _super);
  14365. function TransformNode(name, scene, isPure) {
  14366. if (scene === void 0) { scene = null; }
  14367. if (isPure === void 0) { isPure = true; }
  14368. var _this = _super.call(this, name, scene) || this;
  14369. // Properties
  14370. _this._rotation = BABYLON.Vector3.Zero();
  14371. _this._scaling = BABYLON.Vector3.One();
  14372. _this._isDirty = false;
  14373. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14374. _this.scalingDeterminant = 1;
  14375. _this.infiniteDistance = false;
  14376. _this.position = BABYLON.Vector3.Zero();
  14377. _this._localWorld = BABYLON.Matrix.Zero();
  14378. _this._worldMatrix = BABYLON.Matrix.Zero();
  14379. _this._worldMatrixDeterminant = 0;
  14380. _this._absolutePosition = BABYLON.Vector3.Zero();
  14381. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14382. _this._postMultiplyPivotMatrix = false;
  14383. _this._isWorldMatrixFrozen = false;
  14384. /**
  14385. * An event triggered after the world matrix is updated
  14386. * @type {BABYLON.Observable}
  14387. */
  14388. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14389. _this._nonUniformScaling = false;
  14390. if (isPure) {
  14391. _this.getScene().addTransformNode(_this);
  14392. }
  14393. return _this;
  14394. }
  14395. Object.defineProperty(TransformNode.prototype, "rotation", {
  14396. /**
  14397. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14398. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14399. * Default : (0.0, 0.0, 0.0)
  14400. */
  14401. get: function () {
  14402. return this._rotation;
  14403. },
  14404. set: function (newRotation) {
  14405. this._rotation = newRotation;
  14406. },
  14407. enumerable: true,
  14408. configurable: true
  14409. });
  14410. Object.defineProperty(TransformNode.prototype, "scaling", {
  14411. /**
  14412. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14413. * Default : (1.0, 1.0, 1.0)
  14414. */
  14415. get: function () {
  14416. return this._scaling;
  14417. },
  14418. /**
  14419. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14420. * Default : (1.0, 1.0, 1.0)
  14421. */
  14422. set: function (newScaling) {
  14423. this._scaling = newScaling;
  14424. },
  14425. enumerable: true,
  14426. configurable: true
  14427. });
  14428. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14429. /**
  14430. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14431. * It's null by default.
  14432. * 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)
  14433. */
  14434. get: function () {
  14435. return this._rotationQuaternion;
  14436. },
  14437. set: function (quaternion) {
  14438. this._rotationQuaternion = quaternion;
  14439. //reset the rotation vector.
  14440. if (quaternion && this.rotation.length()) {
  14441. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14442. }
  14443. },
  14444. enumerable: true,
  14445. configurable: true
  14446. });
  14447. /**
  14448. * Returns the latest update of the World matrix
  14449. * Returns a Matrix.
  14450. */
  14451. TransformNode.prototype.getWorldMatrix = function () {
  14452. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14453. this.computeWorldMatrix();
  14454. }
  14455. return this._worldMatrix;
  14456. };
  14457. /**
  14458. * Returns the latest update of the World matrix determinant.
  14459. */
  14460. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  14461. return this._worldMatrixDeterminant;
  14462. };
  14463. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14464. /**
  14465. * Returns directly the latest state of the mesh World matrix.
  14466. * A Matrix is returned.
  14467. */
  14468. get: function () {
  14469. return this._worldMatrix;
  14470. },
  14471. enumerable: true,
  14472. configurable: true
  14473. });
  14474. /**
  14475. * Copies the paramater passed Matrix into the mesh Pose matrix.
  14476. * Returns the AbstractMesh.
  14477. */
  14478. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  14479. this._poseMatrix.copyFrom(matrix);
  14480. return this;
  14481. };
  14482. /**
  14483. * Returns the mesh Pose matrix.
  14484. * Returned object : Matrix
  14485. */
  14486. TransformNode.prototype.getPoseMatrix = function () {
  14487. return this._poseMatrix;
  14488. };
  14489. TransformNode.prototype._isSynchronized = function () {
  14490. if (this._isDirty) {
  14491. return false;
  14492. }
  14493. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  14494. return false;
  14495. if (this._cache.pivotMatrixUpdated) {
  14496. return false;
  14497. }
  14498. if (this.infiniteDistance) {
  14499. return false;
  14500. }
  14501. if (!this._cache.position.equals(this.position))
  14502. return false;
  14503. if (this.rotationQuaternion) {
  14504. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14505. return false;
  14506. }
  14507. if (!this._cache.rotation.equals(this.rotation))
  14508. return false;
  14509. if (!this._cache.scaling.equals(this.scaling))
  14510. return false;
  14511. return true;
  14512. };
  14513. TransformNode.prototype._initCache = function () {
  14514. _super.prototype._initCache.call(this);
  14515. this._cache.localMatrixUpdated = false;
  14516. this._cache.position = BABYLON.Vector3.Zero();
  14517. this._cache.scaling = BABYLON.Vector3.Zero();
  14518. this._cache.rotation = BABYLON.Vector3.Zero();
  14519. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14520. this._cache.billboardMode = -1;
  14521. };
  14522. TransformNode.prototype.markAsDirty = function (property) {
  14523. if (property === "rotation") {
  14524. this.rotationQuaternion = null;
  14525. }
  14526. this._currentRenderId = Number.MAX_VALUE;
  14527. this._isDirty = true;
  14528. return this;
  14529. };
  14530. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  14531. /**
  14532. * Returns the current mesh absolute position.
  14533. * Retuns a Vector3.
  14534. */
  14535. get: function () {
  14536. return this._absolutePosition;
  14537. },
  14538. enumerable: true,
  14539. configurable: true
  14540. });
  14541. /**
  14542. * Sets a new pivot matrix to the mesh.
  14543. * Returns the AbstractMesh.
  14544. */
  14545. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14546. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14547. this._pivotMatrix = matrix.clone();
  14548. this._cache.pivotMatrixUpdated = true;
  14549. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14550. if (this._postMultiplyPivotMatrix) {
  14551. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14552. }
  14553. return this;
  14554. };
  14555. /**
  14556. * Returns the mesh pivot matrix.
  14557. * Default : Identity.
  14558. * A Matrix is returned.
  14559. */
  14560. TransformNode.prototype.getPivotMatrix = function () {
  14561. return this._pivotMatrix;
  14562. };
  14563. /**
  14564. * Prevents the World matrix to be computed any longer.
  14565. * Returns the AbstractMesh.
  14566. */
  14567. TransformNode.prototype.freezeWorldMatrix = function () {
  14568. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  14569. this.computeWorldMatrix(true);
  14570. this._isWorldMatrixFrozen = true;
  14571. return this;
  14572. };
  14573. /**
  14574. * Allows back the World matrix computation.
  14575. * Returns the AbstractMesh.
  14576. */
  14577. TransformNode.prototype.unfreezeWorldMatrix = function () {
  14578. this._isWorldMatrixFrozen = false;
  14579. this.computeWorldMatrix(true);
  14580. return this;
  14581. };
  14582. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  14583. /**
  14584. * True if the World matrix has been frozen.
  14585. * Returns a boolean.
  14586. */
  14587. get: function () {
  14588. return this._isWorldMatrixFrozen;
  14589. },
  14590. enumerable: true,
  14591. configurable: true
  14592. });
  14593. /**
  14594. * Retuns the mesh absolute position in the World.
  14595. * Returns a Vector3.
  14596. */
  14597. TransformNode.prototype.getAbsolutePosition = function () {
  14598. this.computeWorldMatrix();
  14599. return this._absolutePosition;
  14600. };
  14601. /**
  14602. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  14603. * Returns the AbstractMesh.
  14604. */
  14605. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  14606. if (!absolutePosition) {
  14607. return this;
  14608. }
  14609. var absolutePositionX;
  14610. var absolutePositionY;
  14611. var absolutePositionZ;
  14612. if (absolutePosition.x === undefined) {
  14613. if (arguments.length < 3) {
  14614. return this;
  14615. }
  14616. absolutePositionX = arguments[0];
  14617. absolutePositionY = arguments[1];
  14618. absolutePositionZ = arguments[2];
  14619. }
  14620. else {
  14621. absolutePositionX = absolutePosition.x;
  14622. absolutePositionY = absolutePosition.y;
  14623. absolutePositionZ = absolutePosition.z;
  14624. }
  14625. if (this.parent) {
  14626. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14627. invertParentWorldMatrix.invert();
  14628. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14629. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14630. }
  14631. else {
  14632. this.position.x = absolutePositionX;
  14633. this.position.y = absolutePositionY;
  14634. this.position.z = absolutePositionZ;
  14635. }
  14636. return this;
  14637. };
  14638. /**
  14639. * Sets the mesh position in its local space.
  14640. * Returns the AbstractMesh.
  14641. */
  14642. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  14643. this.computeWorldMatrix();
  14644. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14645. return this;
  14646. };
  14647. /**
  14648. * Returns the mesh position in the local space from the current World matrix values.
  14649. * Returns a new Vector3.
  14650. */
  14651. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  14652. this.computeWorldMatrix();
  14653. var invLocalWorldMatrix = this._localWorld.clone();
  14654. invLocalWorldMatrix.invert();
  14655. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14656. };
  14657. /**
  14658. * Translates the mesh along the passed Vector3 in its local space.
  14659. * Returns the AbstractMesh.
  14660. */
  14661. TransformNode.prototype.locallyTranslate = function (vector3) {
  14662. this.computeWorldMatrix(true);
  14663. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14664. return this;
  14665. };
  14666. /**
  14667. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  14668. * @param targetPoint the position (must be in same space as current mesh) to look at
  14669. * @param yawCor optional yaw (y-axis) correction in radians
  14670. * @param pitchCor optional pitch (x-axis) correction in radians
  14671. * @param rollCor optional roll (z-axis) correction in radians
  14672. * @param space the choosen space of the target
  14673. * @returns the TransformNode.
  14674. */
  14675. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14676. if (yawCor === void 0) { yawCor = 0; }
  14677. if (pitchCor === void 0) { pitchCor = 0; }
  14678. if (rollCor === void 0) { rollCor = 0; }
  14679. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14680. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  14681. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14682. targetPoint.subtractToRef(pos, dv);
  14683. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14684. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14685. var pitch = Math.atan2(dv.y, len);
  14686. if (this.rotationQuaternion) {
  14687. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14688. }
  14689. else {
  14690. this.rotation.x = pitch + pitchCor;
  14691. this.rotation.y = yaw + yawCor;
  14692. this.rotation.z = rollCor;
  14693. }
  14694. return this;
  14695. };
  14696. /**
  14697. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14698. * This Vector3 is expressed in the World space.
  14699. */
  14700. TransformNode.prototype.getDirection = function (localAxis) {
  14701. var result = BABYLON.Vector3.Zero();
  14702. this.getDirectionToRef(localAxis, result);
  14703. return result;
  14704. };
  14705. /**
  14706. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14707. * localAxis is expressed in the mesh local space.
  14708. * result is computed in the Wordl space from the mesh World matrix.
  14709. * Returns the AbstractMesh.
  14710. */
  14711. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  14712. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14713. return this;
  14714. };
  14715. TransformNode.prototype.setPivotPoint = function (point, space) {
  14716. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14717. if (this.getScene().getRenderId() == 0) {
  14718. this.computeWorldMatrix(true);
  14719. }
  14720. var wm = this.getWorldMatrix();
  14721. if (space == BABYLON.Space.WORLD) {
  14722. var tmat = BABYLON.Tmp.Matrix[0];
  14723. wm.invertToRef(tmat);
  14724. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14725. }
  14726. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14727. this._pivotMatrix.m[12] = -point.x;
  14728. this._pivotMatrix.m[13] = -point.y;
  14729. this._pivotMatrix.m[14] = -point.z;
  14730. this._cache.pivotMatrixUpdated = true;
  14731. return this;
  14732. };
  14733. /**
  14734. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14735. */
  14736. TransformNode.prototype.getPivotPoint = function () {
  14737. var point = BABYLON.Vector3.Zero();
  14738. this.getPivotPointToRef(point);
  14739. return point;
  14740. };
  14741. /**
  14742. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14743. * Returns the AbstractMesh.
  14744. */
  14745. TransformNode.prototype.getPivotPointToRef = function (result) {
  14746. result.x = -this._pivotMatrix.m[12];
  14747. result.y = -this._pivotMatrix.m[13];
  14748. result.z = -this._pivotMatrix.m[14];
  14749. return this;
  14750. };
  14751. /**
  14752. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14753. */
  14754. TransformNode.prototype.getAbsolutePivotPoint = function () {
  14755. var point = BABYLON.Vector3.Zero();
  14756. this.getAbsolutePivotPointToRef(point);
  14757. return point;
  14758. };
  14759. /**
  14760. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14761. * Returns the AbstractMesh.
  14762. */
  14763. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  14764. result.x = this._pivotMatrix.m[12];
  14765. result.y = this._pivotMatrix.m[13];
  14766. result.z = this._pivotMatrix.m[14];
  14767. this.getPivotPointToRef(result);
  14768. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14769. return this;
  14770. };
  14771. /**
  14772. * Defines the passed node as the parent of the current node.
  14773. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  14774. * Returns the TransformNode.
  14775. */
  14776. TransformNode.prototype.setParent = function (node) {
  14777. if (node === null) {
  14778. var rotation = BABYLON.Tmp.Quaternion[0];
  14779. var position = BABYLON.Tmp.Vector3[0];
  14780. var scale = BABYLON.Tmp.Vector3[1];
  14781. if (this.parent && this.parent.computeWorldMatrix) {
  14782. this.parent.computeWorldMatrix(true);
  14783. }
  14784. this.computeWorldMatrix(true);
  14785. this.getWorldMatrix().decompose(scale, rotation, position);
  14786. if (this.rotationQuaternion) {
  14787. this.rotationQuaternion.copyFrom(rotation);
  14788. }
  14789. else {
  14790. rotation.toEulerAnglesToRef(this.rotation);
  14791. }
  14792. this.scaling.x = scale.x;
  14793. this.scaling.y = scale.y;
  14794. this.scaling.z = scale.z;
  14795. this.position.x = position.x;
  14796. this.position.y = position.y;
  14797. this.position.z = position.z;
  14798. }
  14799. else {
  14800. var rotation = BABYLON.Tmp.Quaternion[0];
  14801. var position = BABYLON.Tmp.Vector3[0];
  14802. var scale = BABYLON.Tmp.Vector3[1];
  14803. var diffMatrix = BABYLON.Tmp.Matrix[0];
  14804. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  14805. this.computeWorldMatrix(true);
  14806. node.computeWorldMatrix(true);
  14807. node.getWorldMatrix().invertToRef(invParentMatrix);
  14808. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  14809. diffMatrix.decompose(scale, rotation, position);
  14810. if (this.rotationQuaternion) {
  14811. this.rotationQuaternion.copyFrom(rotation);
  14812. }
  14813. else {
  14814. rotation.toEulerAnglesToRef(this.rotation);
  14815. }
  14816. this.position.x = position.x;
  14817. this.position.y = position.y;
  14818. this.position.z = position.z;
  14819. this.scaling.x = scale.x;
  14820. this.scaling.y = scale.y;
  14821. this.scaling.z = scale.z;
  14822. }
  14823. this.parent = node;
  14824. return this;
  14825. };
  14826. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  14827. get: function () {
  14828. return this._nonUniformScaling;
  14829. },
  14830. enumerable: true,
  14831. configurable: true
  14832. });
  14833. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  14834. if (this._nonUniformScaling === value) {
  14835. return false;
  14836. }
  14837. this._nonUniformScaling = true;
  14838. return true;
  14839. };
  14840. /**
  14841. * Attach the current TransformNode to another TransformNode associated with a bone
  14842. * @param bone Bone affecting the TransformNode
  14843. * @param affectedTransformNode TransformNode associated with the bone
  14844. */
  14845. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  14846. this._transformToBoneReferal = affectedTransformNode;
  14847. this.parent = bone;
  14848. if (bone.getWorldMatrix().determinant() < 0) {
  14849. this.scalingDeterminant *= -1;
  14850. }
  14851. return this;
  14852. };
  14853. TransformNode.prototype.detachFromBone = function () {
  14854. if (!this.parent) {
  14855. return this;
  14856. }
  14857. if (this.parent.getWorldMatrix().determinant() < 0) {
  14858. this.scalingDeterminant *= -1;
  14859. }
  14860. this._transformToBoneReferal = null;
  14861. this.parent = null;
  14862. return this;
  14863. };
  14864. /**
  14865. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  14866. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14867. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14868. * The passed axis is also normalized.
  14869. * Returns the AbstractMesh.
  14870. */
  14871. TransformNode.prototype.rotate = function (axis, amount, space) {
  14872. axis.normalize();
  14873. if (!this.rotationQuaternion) {
  14874. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14875. this.rotation = BABYLON.Vector3.Zero();
  14876. }
  14877. var rotationQuaternion;
  14878. if (!space || space === BABYLON.Space.LOCAL) {
  14879. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14880. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  14881. }
  14882. else {
  14883. if (this.parent) {
  14884. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14885. invertParentWorldMatrix.invert();
  14886. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  14887. }
  14888. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14889. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14890. }
  14891. return this;
  14892. };
  14893. /**
  14894. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  14895. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14896. * The passed axis is also normalized.
  14897. * Returns the AbstractMesh.
  14898. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  14899. */
  14900. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  14901. axis.normalize();
  14902. if (!this.rotationQuaternion) {
  14903. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14904. this.rotation.copyFromFloats(0, 0, 0);
  14905. }
  14906. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  14907. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  14908. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  14909. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  14910. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  14911. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  14912. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  14913. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  14914. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14915. return this;
  14916. };
  14917. /**
  14918. * Translates the mesh along the axis vector for the passed distance in the given space.
  14919. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14920. * Returns the AbstractMesh.
  14921. */
  14922. TransformNode.prototype.translate = function (axis, distance, space) {
  14923. var displacementVector = axis.scale(distance);
  14924. if (!space || space === BABYLON.Space.LOCAL) {
  14925. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  14926. this.setPositionWithLocalVector(tempV3);
  14927. }
  14928. else {
  14929. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  14930. }
  14931. return this;
  14932. };
  14933. /**
  14934. * Adds a rotation step to the mesh current rotation.
  14935. * x, y, z are Euler angles expressed in radians.
  14936. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  14937. * This means this rotation is made in the mesh local space only.
  14938. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  14939. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  14940. * ```javascript
  14941. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  14942. * ```
  14943. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  14944. * 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.
  14945. * Returns the AbstractMesh.
  14946. */
  14947. TransformNode.prototype.addRotation = function (x, y, z) {
  14948. var rotationQuaternion;
  14949. if (this.rotationQuaternion) {
  14950. rotationQuaternion = this.rotationQuaternion;
  14951. }
  14952. else {
  14953. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  14954. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  14955. }
  14956. var accumulation = BABYLON.Tmp.Quaternion[0];
  14957. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  14958. rotationQuaternion.multiplyInPlace(accumulation);
  14959. if (!this.rotationQuaternion) {
  14960. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  14961. }
  14962. return this;
  14963. };
  14964. /**
  14965. * Computes the mesh World matrix and returns it.
  14966. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14967. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14968. * If the parameter `force`is set to `true`, the actual computation is done.
  14969. * Returns the mesh World Matrix.
  14970. */
  14971. TransformNode.prototype.computeWorldMatrix = function (force) {
  14972. if (this._isWorldMatrixFrozen) {
  14973. return this._worldMatrix;
  14974. }
  14975. if (!force && this.isSynchronized(true)) {
  14976. return this._worldMatrix;
  14977. }
  14978. this._cache.position.copyFrom(this.position);
  14979. this._cache.scaling.copyFrom(this.scaling);
  14980. this._cache.pivotMatrixUpdated = false;
  14981. this._cache.billboardMode = this.billboardMode;
  14982. this._currentRenderId = this.getScene().getRenderId();
  14983. this._isDirty = false;
  14984. // Scaling
  14985. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14986. // Rotation
  14987. //rotate, if quaternion is set and rotation was used
  14988. if (this.rotationQuaternion) {
  14989. var len = this.rotation.length();
  14990. if (len) {
  14991. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14992. this.rotation.copyFromFloats(0, 0, 0);
  14993. }
  14994. }
  14995. if (this.rotationQuaternion) {
  14996. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14997. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14998. }
  14999. else {
  15000. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  15001. this._cache.rotation.copyFrom(this.rotation);
  15002. }
  15003. // Translation
  15004. var camera = this.getScene().activeCamera;
  15005. if (this.infiniteDistance && !this.parent && camera) {
  15006. var cameraWorldMatrix = camera.getWorldMatrix();
  15007. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  15008. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  15009. }
  15010. else {
  15011. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  15012. }
  15013. // Composing transformations
  15014. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15015. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15016. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15017. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15018. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15019. // Need to decompose each rotation here
  15020. var currentPosition = BABYLON.Tmp.Vector3[3];
  15021. if (this.parent && this.parent.getWorldMatrix) {
  15022. if (this._transformToBoneReferal) {
  15023. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15024. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15025. }
  15026. else {
  15027. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15028. }
  15029. }
  15030. else {
  15031. currentPosition.copyFrom(this.position);
  15032. }
  15033. currentPosition.subtractInPlace(camera.globalPosition);
  15034. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15035. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15036. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15037. }
  15038. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15039. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15040. }
  15041. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15042. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15043. }
  15044. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15045. }
  15046. else {
  15047. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15048. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15049. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15050. }
  15051. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15052. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15053. }
  15054. // Local world
  15055. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15056. // Parent
  15057. if (this.parent && this.parent.getWorldMatrix) {
  15058. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15059. if (this._transformToBoneReferal) {
  15060. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15061. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15062. }
  15063. else {
  15064. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15065. }
  15066. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15067. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15068. this._worldMatrix.copyFrom(this._localWorld);
  15069. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15070. }
  15071. else {
  15072. if (this._transformToBoneReferal) {
  15073. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15074. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15075. }
  15076. else {
  15077. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15078. }
  15079. }
  15080. this._markSyncedWithParent();
  15081. }
  15082. else {
  15083. this._worldMatrix.copyFrom(this._localWorld);
  15084. }
  15085. // Post multiply inverse of pivotMatrix
  15086. if (this._postMultiplyPivotMatrix) {
  15087. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15088. }
  15089. // Normal matrix
  15090. if (this.scaling.isNonUniform) {
  15091. this._updateNonUniformScalingState(true);
  15092. }
  15093. else if (this.parent && this.parent._nonUniformScaling) {
  15094. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15095. }
  15096. else {
  15097. this._updateNonUniformScalingState(false);
  15098. }
  15099. this._afterComputeWorldMatrix();
  15100. // Absolute position
  15101. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15102. // Callbacks
  15103. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15104. if (!this._poseMatrix) {
  15105. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15106. }
  15107. // Cache the determinant
  15108. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15109. return this._worldMatrix;
  15110. };
  15111. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15112. };
  15113. /**
  15114. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15115. * @param func: callback function to add
  15116. *
  15117. * Returns the TransformNode.
  15118. */
  15119. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15120. this.onAfterWorldMatrixUpdateObservable.add(func);
  15121. return this;
  15122. };
  15123. /**
  15124. * Removes a registered callback function.
  15125. * Returns the TransformNode.
  15126. */
  15127. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15128. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15129. return this;
  15130. };
  15131. /**
  15132. * Clone the current transform node
  15133. * Returns the new transform node
  15134. * @param name Name of the new clone
  15135. * @param newParent New parent for the clone
  15136. * @param doNotCloneChildren Do not clone children hierarchy
  15137. */
  15138. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15139. var _this = this;
  15140. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15141. result.name = name;
  15142. result.id = name;
  15143. if (newParent) {
  15144. result.parent = newParent;
  15145. }
  15146. if (!doNotCloneChildren) {
  15147. // Children
  15148. var directDescendants = this.getDescendants(true);
  15149. for (var index = 0; index < directDescendants.length; index++) {
  15150. var child = directDescendants[index];
  15151. if (child.clone) {
  15152. child.clone(name + "." + child.name, result);
  15153. }
  15154. }
  15155. }
  15156. return result;
  15157. };
  15158. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15159. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15160. serializationObject.type = this.getClassName();
  15161. // Parent
  15162. if (this.parent) {
  15163. serializationObject.parentId = this.parent.id;
  15164. }
  15165. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15166. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15167. }
  15168. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15169. serializationObject.isEnabled = this.isEnabled();
  15170. // Parent
  15171. if (this.parent) {
  15172. serializationObject.parentId = this.parent.id;
  15173. }
  15174. return serializationObject;
  15175. };
  15176. // Statics
  15177. /**
  15178. * Returns a new TransformNode object parsed from the source provided.
  15179. * The parameter `parsedMesh` is the source.
  15180. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15181. */
  15182. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15183. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15184. if (BABYLON.Tags) {
  15185. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15186. }
  15187. if (parsedTransformNode.localMatrix) {
  15188. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15189. }
  15190. else if (parsedTransformNode.pivotMatrix) {
  15191. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15192. }
  15193. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15194. // Parent
  15195. if (parsedTransformNode.parentId) {
  15196. transformNode._waitingParentId = parsedTransformNode.parentId;
  15197. }
  15198. return transformNode;
  15199. };
  15200. /**
  15201. * Disposes the TransformNode.
  15202. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15203. * Returns nothing.
  15204. */
  15205. TransformNode.prototype.dispose = function (doNotRecurse) {
  15206. // Animations
  15207. this.getScene().stopAnimation(this);
  15208. // Remove from scene
  15209. this.getScene().removeTransformNode(this);
  15210. if (!doNotRecurse) {
  15211. // Children
  15212. var objects = this.getDescendants(true);
  15213. for (var index = 0; index < objects.length; index++) {
  15214. objects[index].dispose();
  15215. }
  15216. }
  15217. else {
  15218. var childMeshes = this.getChildMeshes(true);
  15219. for (index = 0; index < childMeshes.length; index++) {
  15220. var child = childMeshes[index];
  15221. child.parent = null;
  15222. child.computeWorldMatrix(true);
  15223. }
  15224. }
  15225. this.onAfterWorldMatrixUpdateObservable.clear();
  15226. _super.prototype.dispose.call(this);
  15227. };
  15228. // Statics
  15229. TransformNode.BILLBOARDMODE_NONE = 0;
  15230. TransformNode.BILLBOARDMODE_X = 1;
  15231. TransformNode.BILLBOARDMODE_Y = 2;
  15232. TransformNode.BILLBOARDMODE_Z = 4;
  15233. TransformNode.BILLBOARDMODE_ALL = 7;
  15234. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15235. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15236. __decorate([
  15237. BABYLON.serializeAsVector3()
  15238. ], TransformNode.prototype, "_rotation", void 0);
  15239. __decorate([
  15240. BABYLON.serializeAsQuaternion()
  15241. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15242. __decorate([
  15243. BABYLON.serializeAsVector3()
  15244. ], TransformNode.prototype, "_scaling", void 0);
  15245. __decorate([
  15246. BABYLON.serialize()
  15247. ], TransformNode.prototype, "billboardMode", void 0);
  15248. __decorate([
  15249. BABYLON.serialize()
  15250. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15251. __decorate([
  15252. BABYLON.serialize()
  15253. ], TransformNode.prototype, "infiniteDistance", void 0);
  15254. __decorate([
  15255. BABYLON.serializeAsVector3()
  15256. ], TransformNode.prototype, "position", void 0);
  15257. return TransformNode;
  15258. }(BABYLON.Node));
  15259. BABYLON.TransformNode = TransformNode;
  15260. })(BABYLON || (BABYLON = {}));
  15261. //# sourceMappingURL=babylon.transformNode.js.map
  15262. var BABYLON;
  15263. (function (BABYLON) {
  15264. var AbstractMesh = /** @class */ (function (_super) {
  15265. __extends(AbstractMesh, _super);
  15266. // Constructor
  15267. function AbstractMesh(name, scene) {
  15268. if (scene === void 0) { scene = null; }
  15269. var _this = _super.call(this, name, scene, false) || this;
  15270. _this._facetNb = 0; // facet number
  15271. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15272. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15273. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15274. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15275. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15276. _this._subDiv = {
  15277. max: 1,
  15278. X: 1,
  15279. Y: 1,
  15280. Z: 1
  15281. };
  15282. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15283. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15284. // Events
  15285. /**
  15286. * An event triggered when this mesh collides with another one
  15287. * @type {BABYLON.Observable}
  15288. */
  15289. _this.onCollideObservable = new BABYLON.Observable();
  15290. /**
  15291. * An event triggered when the collision's position changes
  15292. * @type {BABYLON.Observable}
  15293. */
  15294. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15295. /**
  15296. * An event triggered when material is changed
  15297. * @type {BABYLON.Observable}
  15298. */
  15299. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15300. // Properties
  15301. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15302. /**
  15303. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15304. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15305. * or
  15306. * 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.
  15307. * for more info check WebGl documentations
  15308. */
  15309. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15310. /**
  15311. * 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:
  15312. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15313. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15314. * 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.
  15315. */
  15316. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15317. /**
  15318. * 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.
  15319. * The default value is -1 which means don't break the query and wait till the result.
  15320. */
  15321. _this.occlusionRetryCount = -1;
  15322. _this._occlusionInternalRetryCounter = 0;
  15323. _this._isOccluded = false;
  15324. _this._isOcclusionQueryInProgress = false;
  15325. _this.visibility = 1.0;
  15326. _this.alphaIndex = Number.MAX_VALUE;
  15327. _this.isVisible = true;
  15328. _this.isPickable = true;
  15329. _this.showBoundingBox = false;
  15330. _this.showSubMeshesBoundingBox = false;
  15331. _this.isBlocker = false;
  15332. _this.enablePointerMoveEvents = false;
  15333. _this.renderingGroupId = 0;
  15334. _this._receiveShadows = false;
  15335. _this.renderOutline = false;
  15336. _this.outlineColor = BABYLON.Color3.Red();
  15337. _this.outlineWidth = 0.02;
  15338. _this.renderOverlay = false;
  15339. _this.overlayColor = BABYLON.Color3.Red();
  15340. _this.overlayAlpha = 0.5;
  15341. _this._hasVertexAlpha = false;
  15342. _this._useVertexColors = true;
  15343. _this._computeBonesUsingShaders = true;
  15344. _this._numBoneInfluencers = 4;
  15345. _this._applyFog = true;
  15346. _this.useOctreeForRenderingSelection = true;
  15347. _this.useOctreeForPicking = true;
  15348. _this.useOctreeForCollisions = true;
  15349. _this._layerMask = 0x0FFFFFFF;
  15350. /**
  15351. * True if the mesh must be rendered in any case.
  15352. */
  15353. _this.alwaysSelectAsActiveMesh = false;
  15354. /**
  15355. * This scene's action manager
  15356. * @type {BABYLON.ActionManager}
  15357. */
  15358. _this.actionManager = null;
  15359. // Physics
  15360. _this.physicsImpostor = null;
  15361. // Collisions
  15362. _this._checkCollisions = false;
  15363. _this._collisionMask = -1;
  15364. _this._collisionGroup = -1;
  15365. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15366. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15367. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15368. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15369. // Edges
  15370. _this.edgesWidth = 1;
  15371. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15372. // Cache
  15373. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15374. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15375. _this._isDisposed = false;
  15376. _this._renderId = 0;
  15377. _this._intersectionsInProgress = new Array();
  15378. _this._unIndexed = false;
  15379. _this._lightSources = new Array();
  15380. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15381. if (collidedMesh === void 0) { collidedMesh = null; }
  15382. //TODO move this to the collision coordinator!
  15383. if (_this.getScene().workerCollisions)
  15384. newPosition.multiplyInPlace(_this._collider._radius);
  15385. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15386. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15387. _this.position.addInPlace(_this._diffPositionForCollisions);
  15388. }
  15389. if (collidedMesh) {
  15390. _this.onCollideObservable.notifyObservers(collidedMesh);
  15391. }
  15392. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15393. };
  15394. _this.getScene().addMesh(_this);
  15395. _this._resyncLightSources();
  15396. return _this;
  15397. }
  15398. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15399. get: function () {
  15400. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15401. },
  15402. enumerable: true,
  15403. configurable: true
  15404. });
  15405. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15406. get: function () {
  15407. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15408. },
  15409. enumerable: true,
  15410. configurable: true
  15411. });
  15412. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15413. get: function () {
  15414. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15415. },
  15416. enumerable: true,
  15417. configurable: true
  15418. });
  15419. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15420. get: function () {
  15421. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15422. },
  15423. enumerable: true,
  15424. configurable: true
  15425. });
  15426. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15427. get: function () {
  15428. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15429. },
  15430. enumerable: true,
  15431. configurable: true
  15432. });
  15433. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15434. /**
  15435. * Read-only : the number of facets in the mesh
  15436. */
  15437. get: function () {
  15438. return this._facetNb;
  15439. },
  15440. enumerable: true,
  15441. configurable: true
  15442. });
  15443. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15444. /**
  15445. * The number (integer) of subdivisions per axis in the partioning space
  15446. */
  15447. get: function () {
  15448. return this._partitioningSubdivisions;
  15449. },
  15450. set: function (nb) {
  15451. this._partitioningSubdivisions = nb;
  15452. },
  15453. enumerable: true,
  15454. configurable: true
  15455. });
  15456. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15457. /**
  15458. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15459. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15460. */
  15461. get: function () {
  15462. return this._partitioningBBoxRatio;
  15463. },
  15464. set: function (ratio) {
  15465. this._partitioningBBoxRatio = ratio;
  15466. },
  15467. enumerable: true,
  15468. configurable: true
  15469. });
  15470. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  15471. /**
  15472. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  15473. * Works only for updatable meshes.
  15474. * Doesn't work with multi-materials.
  15475. */
  15476. get: function () {
  15477. return this._facetDepthSort;
  15478. },
  15479. set: function (sort) {
  15480. this._facetDepthSort = sort;
  15481. },
  15482. enumerable: true,
  15483. configurable: true
  15484. });
  15485. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  15486. /**
  15487. * The location (Vector3) where the facet depth sort must be computed from.
  15488. * By default, the active camera position.
  15489. * Used only when facet depth sort is enabled.
  15490. */
  15491. get: function () {
  15492. return this._facetDepthSortFrom;
  15493. },
  15494. set: function (location) {
  15495. this._facetDepthSortFrom = location;
  15496. },
  15497. enumerable: true,
  15498. configurable: true
  15499. });
  15500. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  15501. /**
  15502. * Read-only boolean : is the feature facetData enabled ?
  15503. */
  15504. get: function () {
  15505. return this._facetDataEnabled;
  15506. },
  15507. enumerable: true,
  15508. configurable: true
  15509. });
  15510. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  15511. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  15512. return false;
  15513. }
  15514. this._markSubMeshesAsMiscDirty();
  15515. return true;
  15516. };
  15517. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  15518. set: function (callback) {
  15519. if (this._onCollideObserver) {
  15520. this.onCollideObservable.remove(this._onCollideObserver);
  15521. }
  15522. this._onCollideObserver = this.onCollideObservable.add(callback);
  15523. },
  15524. enumerable: true,
  15525. configurable: true
  15526. });
  15527. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  15528. set: function (callback) {
  15529. if (this._onCollisionPositionChangeObserver) {
  15530. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  15531. }
  15532. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  15533. },
  15534. enumerable: true,
  15535. configurable: true
  15536. });
  15537. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  15538. /**
  15539. * 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.
  15540. */
  15541. get: function () {
  15542. return this._isOccluded;
  15543. },
  15544. set: function (value) {
  15545. this._isOccluded = value;
  15546. },
  15547. enumerable: true,
  15548. configurable: true
  15549. });
  15550. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  15551. /**
  15552. * Flag to check the progress status of the query
  15553. */
  15554. get: function () {
  15555. return this._isOcclusionQueryInProgress;
  15556. },
  15557. enumerable: true,
  15558. configurable: true
  15559. });
  15560. Object.defineProperty(AbstractMesh.prototype, "material", {
  15561. get: function () {
  15562. return this._material;
  15563. },
  15564. set: function (value) {
  15565. if (this._material === value) {
  15566. return;
  15567. }
  15568. this._material = value;
  15569. if (this.onMaterialChangedObservable.hasObservers) {
  15570. this.onMaterialChangedObservable.notifyObservers(this);
  15571. }
  15572. if (!this.subMeshes) {
  15573. return;
  15574. }
  15575. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15576. var subMesh = _a[_i];
  15577. subMesh.setEffect(null);
  15578. }
  15579. },
  15580. enumerable: true,
  15581. configurable: true
  15582. });
  15583. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  15584. get: function () {
  15585. return this._receiveShadows;
  15586. },
  15587. set: function (value) {
  15588. if (this._receiveShadows === value) {
  15589. return;
  15590. }
  15591. this._receiveShadows = value;
  15592. this._markSubMeshesAsLightDirty();
  15593. },
  15594. enumerable: true,
  15595. configurable: true
  15596. });
  15597. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  15598. get: function () {
  15599. return this._hasVertexAlpha;
  15600. },
  15601. set: function (value) {
  15602. if (this._hasVertexAlpha === value) {
  15603. return;
  15604. }
  15605. this._hasVertexAlpha = value;
  15606. this._markSubMeshesAsAttributesDirty();
  15607. },
  15608. enumerable: true,
  15609. configurable: true
  15610. });
  15611. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  15612. get: function () {
  15613. return this._useVertexColors;
  15614. },
  15615. set: function (value) {
  15616. if (this._useVertexColors === value) {
  15617. return;
  15618. }
  15619. this._useVertexColors = value;
  15620. this._markSubMeshesAsAttributesDirty();
  15621. },
  15622. enumerable: true,
  15623. configurable: true
  15624. });
  15625. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  15626. get: function () {
  15627. return this._computeBonesUsingShaders;
  15628. },
  15629. set: function (value) {
  15630. if (this._computeBonesUsingShaders === value) {
  15631. return;
  15632. }
  15633. this._computeBonesUsingShaders = value;
  15634. this._markSubMeshesAsAttributesDirty();
  15635. },
  15636. enumerable: true,
  15637. configurable: true
  15638. });
  15639. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  15640. get: function () {
  15641. return this._numBoneInfluencers;
  15642. },
  15643. set: function (value) {
  15644. if (this._numBoneInfluencers === value) {
  15645. return;
  15646. }
  15647. this._numBoneInfluencers = value;
  15648. this._markSubMeshesAsAttributesDirty();
  15649. },
  15650. enumerable: true,
  15651. configurable: true
  15652. });
  15653. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  15654. get: function () {
  15655. return this._applyFog;
  15656. },
  15657. set: function (value) {
  15658. if (this._applyFog === value) {
  15659. return;
  15660. }
  15661. this._applyFog = value;
  15662. this._markSubMeshesAsMiscDirty();
  15663. },
  15664. enumerable: true,
  15665. configurable: true
  15666. });
  15667. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  15668. get: function () {
  15669. return this._layerMask;
  15670. },
  15671. set: function (value) {
  15672. if (value === this._layerMask) {
  15673. return;
  15674. }
  15675. this._layerMask = value;
  15676. this._resyncLightSources();
  15677. },
  15678. enumerable: true,
  15679. configurable: true
  15680. });
  15681. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  15682. get: function () {
  15683. return this._collisionMask;
  15684. },
  15685. set: function (mask) {
  15686. this._collisionMask = !isNaN(mask) ? mask : -1;
  15687. },
  15688. enumerable: true,
  15689. configurable: true
  15690. });
  15691. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  15692. get: function () {
  15693. return this._collisionGroup;
  15694. },
  15695. set: function (mask) {
  15696. this._collisionGroup = !isNaN(mask) ? mask : -1;
  15697. },
  15698. enumerable: true,
  15699. configurable: true
  15700. });
  15701. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  15702. get: function () {
  15703. return null;
  15704. },
  15705. enumerable: true,
  15706. configurable: true
  15707. });
  15708. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  15709. get: function () {
  15710. return this._skeleton;
  15711. },
  15712. set: function (value) {
  15713. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  15714. this._skeleton._unregisterMeshWithPoseMatrix(this);
  15715. }
  15716. if (value && value.needInitialSkinMatrix) {
  15717. value._registerMeshWithPoseMatrix(this);
  15718. }
  15719. this._skeleton = value;
  15720. if (!this._skeleton) {
  15721. this._bonesTransformMatrices = null;
  15722. }
  15723. this._markSubMeshesAsAttributesDirty();
  15724. },
  15725. enumerable: true,
  15726. configurable: true
  15727. });
  15728. /**
  15729. * Boolean : true if the mesh has been disposed.
  15730. */
  15731. AbstractMesh.prototype.isDisposed = function () {
  15732. return this._isDisposed;
  15733. };
  15734. /**
  15735. * Returns the string "AbstractMesh"
  15736. */
  15737. AbstractMesh.prototype.getClassName = function () {
  15738. return "AbstractMesh";
  15739. };
  15740. /**
  15741. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15742. */
  15743. AbstractMesh.prototype.toString = function (fullDetails) {
  15744. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  15745. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  15746. if (this._skeleton) {
  15747. ret += ", skeleton: " + this._skeleton.name;
  15748. }
  15749. if (fullDetails) {
  15750. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  15751. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  15752. }
  15753. return ret;
  15754. };
  15755. AbstractMesh.prototype._rebuild = function () {
  15756. if (this._occlusionQuery) {
  15757. this._occlusionQuery = null;
  15758. }
  15759. if (this._edgesRenderer) {
  15760. this._edgesRenderer._rebuild();
  15761. }
  15762. if (!this.subMeshes) {
  15763. return;
  15764. }
  15765. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15766. var subMesh = _a[_i];
  15767. subMesh._rebuild();
  15768. }
  15769. };
  15770. AbstractMesh.prototype._resyncLightSources = function () {
  15771. this._lightSources.length = 0;
  15772. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  15773. var light = _a[_i];
  15774. if (!light.isEnabled()) {
  15775. continue;
  15776. }
  15777. if (light.canAffectMesh(this)) {
  15778. this._lightSources.push(light);
  15779. }
  15780. }
  15781. this._markSubMeshesAsLightDirty();
  15782. };
  15783. AbstractMesh.prototype._resyncLighSource = function (light) {
  15784. var isIn = light.isEnabled() && light.canAffectMesh(this);
  15785. var index = this._lightSources.indexOf(light);
  15786. if (index === -1) {
  15787. if (!isIn) {
  15788. return;
  15789. }
  15790. this._lightSources.push(light);
  15791. }
  15792. else {
  15793. if (isIn) {
  15794. return;
  15795. }
  15796. this._lightSources.splice(index, 1);
  15797. }
  15798. this._markSubMeshesAsLightDirty();
  15799. };
  15800. AbstractMesh.prototype._removeLightSource = function (light) {
  15801. var index = this._lightSources.indexOf(light);
  15802. if (index === -1) {
  15803. return;
  15804. }
  15805. this._lightSources.splice(index, 1);
  15806. };
  15807. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  15808. if (!this.subMeshes) {
  15809. return;
  15810. }
  15811. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15812. var subMesh = _a[_i];
  15813. if (subMesh._materialDefines) {
  15814. func(subMesh._materialDefines);
  15815. }
  15816. }
  15817. };
  15818. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  15819. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  15820. };
  15821. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  15822. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  15823. };
  15824. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  15825. if (!this.subMeshes) {
  15826. return;
  15827. }
  15828. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15829. var subMesh = _a[_i];
  15830. var material = subMesh.getMaterial();
  15831. if (material) {
  15832. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  15833. }
  15834. }
  15835. };
  15836. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  15837. /**
  15838. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15839. * Default : (1.0, 1.0, 1.0)
  15840. */
  15841. get: function () {
  15842. return this._scaling;
  15843. },
  15844. /**
  15845. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15846. * Default : (1.0, 1.0, 1.0)
  15847. */
  15848. set: function (newScaling) {
  15849. this._scaling = newScaling;
  15850. if (this.physicsImpostor) {
  15851. this.physicsImpostor.forceUpdate();
  15852. }
  15853. },
  15854. enumerable: true,
  15855. configurable: true
  15856. });
  15857. // Methods
  15858. /**
  15859. * Disables the mesh edger rendering mode.
  15860. * Returns the AbstractMesh.
  15861. */
  15862. AbstractMesh.prototype.disableEdgesRendering = function () {
  15863. if (this._edgesRenderer) {
  15864. this._edgesRenderer.dispose();
  15865. this._edgesRenderer = null;
  15866. }
  15867. return this;
  15868. };
  15869. /**
  15870. * Enables the edge rendering mode on the mesh.
  15871. * This mode makes the mesh edges visible.
  15872. * Returns the AbstractMesh.
  15873. */
  15874. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  15875. if (epsilon === void 0) { epsilon = 0.95; }
  15876. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  15877. this.disableEdgesRendering();
  15878. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  15879. return this;
  15880. };
  15881. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  15882. /**
  15883. * Returns true if the mesh is blocked. Used by the class Mesh.
  15884. * Returns the boolean `false` by default.
  15885. */
  15886. get: function () {
  15887. return false;
  15888. },
  15889. enumerable: true,
  15890. configurable: true
  15891. });
  15892. /**
  15893. * Returns the mesh itself by default, used by the class Mesh.
  15894. * Returned type : AbstractMesh
  15895. */
  15896. AbstractMesh.prototype.getLOD = function (camera) {
  15897. return this;
  15898. };
  15899. /**
  15900. * Returns 0 by default, used by the class Mesh.
  15901. * Returns an integer.
  15902. */
  15903. AbstractMesh.prototype.getTotalVertices = function () {
  15904. return 0;
  15905. };
  15906. /**
  15907. * Returns null by default, used by the class Mesh.
  15908. * Returned type : integer array
  15909. */
  15910. AbstractMesh.prototype.getIndices = function () {
  15911. return null;
  15912. };
  15913. /**
  15914. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  15915. * Returned type : float array or Float32Array
  15916. */
  15917. AbstractMesh.prototype.getVerticesData = function (kind) {
  15918. return null;
  15919. };
  15920. /**
  15921. * Sets the vertex data of the mesh geometry for the requested `kind`.
  15922. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  15923. * The `data` are either a numeric array either a Float32Array.
  15924. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  15925. * 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).
  15926. * Note that a new underlying VertexBuffer object is created each call.
  15927. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  15928. *
  15929. * Possible `kind` values :
  15930. * - BABYLON.VertexBuffer.PositionKind
  15931. * - BABYLON.VertexBuffer.UVKind
  15932. * - BABYLON.VertexBuffer.UV2Kind
  15933. * - BABYLON.VertexBuffer.UV3Kind
  15934. * - BABYLON.VertexBuffer.UV4Kind
  15935. * - BABYLON.VertexBuffer.UV5Kind
  15936. * - BABYLON.VertexBuffer.UV6Kind
  15937. * - BABYLON.VertexBuffer.ColorKind
  15938. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15939. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15940. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15941. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15942. *
  15943. * Returns the Mesh.
  15944. */
  15945. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15946. return this;
  15947. };
  15948. /**
  15949. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  15950. * If the mesh has no geometry, it is simply returned as it is.
  15951. * The `data` are either a numeric array either a Float32Array.
  15952. * No new underlying VertexBuffer object is created.
  15953. * 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.
  15954. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  15955. *
  15956. * Possible `kind` values :
  15957. * - BABYLON.VertexBuffer.PositionKind
  15958. * - BABYLON.VertexBuffer.UVKind
  15959. * - BABYLON.VertexBuffer.UV2Kind
  15960. * - BABYLON.VertexBuffer.UV3Kind
  15961. * - BABYLON.VertexBuffer.UV4Kind
  15962. * - BABYLON.VertexBuffer.UV5Kind
  15963. * - BABYLON.VertexBuffer.UV6Kind
  15964. * - BABYLON.VertexBuffer.ColorKind
  15965. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15966. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15967. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15968. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15969. *
  15970. * Returns the Mesh.
  15971. */
  15972. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15973. return this;
  15974. };
  15975. /**
  15976. * Sets the mesh indices.
  15977. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  15978. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  15979. * This method creates a new index buffer each call.
  15980. * Returns the Mesh.
  15981. */
  15982. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  15983. return this;
  15984. };
  15985. /** Returns false by default, used by the class Mesh.
  15986. * Returns a boolean
  15987. */
  15988. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  15989. return false;
  15990. };
  15991. /**
  15992. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  15993. * Returns a BoundingInfo
  15994. */
  15995. AbstractMesh.prototype.getBoundingInfo = function () {
  15996. if (this._masterMesh) {
  15997. return this._masterMesh.getBoundingInfo();
  15998. }
  15999. if (!this._boundingInfo) {
  16000. // this._boundingInfo is being created here
  16001. this._updateBoundingInfo();
  16002. }
  16003. // cannot be null.
  16004. return this._boundingInfo;
  16005. };
  16006. /**
  16007. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  16008. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  16009. */
  16010. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  16011. if (includeDescendants === void 0) { includeDescendants = true; }
  16012. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  16013. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16014. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16015. if (maxDimension === 0) {
  16016. return this;
  16017. }
  16018. var scale = 1 / maxDimension;
  16019. this.scaling.scaleInPlace(scale);
  16020. return this;
  16021. };
  16022. /**
  16023. * Sets a mesh new object BoundingInfo.
  16024. * Returns the AbstractMesh.
  16025. */
  16026. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16027. this._boundingInfo = boundingInfo;
  16028. return this;
  16029. };
  16030. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16031. get: function () {
  16032. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16033. },
  16034. enumerable: true,
  16035. configurable: true
  16036. });
  16037. AbstractMesh.prototype._preActivate = function () {
  16038. };
  16039. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16040. };
  16041. AbstractMesh.prototype._activate = function (renderId) {
  16042. this._renderId = renderId;
  16043. };
  16044. /**
  16045. * Returns the latest update of the World matrix
  16046. * Returns a Matrix.
  16047. */
  16048. AbstractMesh.prototype.getWorldMatrix = function () {
  16049. if (this._masterMesh) {
  16050. return this._masterMesh.getWorldMatrix();
  16051. }
  16052. return _super.prototype.getWorldMatrix.call(this);
  16053. };
  16054. /**
  16055. * Returns the latest update of the World matrix determinant.
  16056. */
  16057. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16058. if (this._masterMesh) {
  16059. return this._masterMesh._getWorldMatrixDeterminant();
  16060. }
  16061. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16062. };
  16063. // ================================== Point of View Movement =================================
  16064. /**
  16065. * Perform relative position change from the point of view of behind the front of the mesh.
  16066. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16067. * Supports definition of mesh facing forward or backward.
  16068. * @param {number} amountRight
  16069. * @param {number} amountUp
  16070. * @param {number} amountForward
  16071. *
  16072. * Returns the AbstractMesh.
  16073. */
  16074. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16075. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16076. return this;
  16077. };
  16078. /**
  16079. * Calculate relative position change from the point of view of behind the front of the mesh.
  16080. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16081. * Supports definition of mesh facing forward or backward.
  16082. * @param {number} amountRight
  16083. * @param {number} amountUp
  16084. * @param {number} amountForward
  16085. *
  16086. * Returns a new Vector3.
  16087. */
  16088. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16089. var rotMatrix = new BABYLON.Matrix();
  16090. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16091. rotQuaternion.toRotationMatrix(rotMatrix);
  16092. var translationDelta = BABYLON.Vector3.Zero();
  16093. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16094. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16095. return translationDelta;
  16096. };
  16097. // ================================== Point of View Rotation =================================
  16098. /**
  16099. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16100. * Supports definition of mesh facing forward or backward.
  16101. * @param {number} flipBack
  16102. * @param {number} twirlClockwise
  16103. * @param {number} tiltRight
  16104. *
  16105. * Returns the AbstractMesh.
  16106. */
  16107. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16108. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16109. return this;
  16110. };
  16111. /**
  16112. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16113. * Supports definition of mesh facing forward or backward.
  16114. * @param {number} flipBack
  16115. * @param {number} twirlClockwise
  16116. * @param {number} tiltRight
  16117. *
  16118. * Returns a new Vector3.
  16119. */
  16120. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16121. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16122. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16123. };
  16124. /**
  16125. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16126. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16127. */
  16128. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16129. if (includeDescendants === void 0) { includeDescendants = true; }
  16130. this.computeWorldMatrix(true);
  16131. var min;
  16132. var max;
  16133. var boundingInfo = this.getBoundingInfo();
  16134. if (!this.subMeshes) {
  16135. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16136. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16137. }
  16138. else {
  16139. min = boundingInfo.boundingBox.minimumWorld;
  16140. max = boundingInfo.boundingBox.maximumWorld;
  16141. }
  16142. if (includeDescendants) {
  16143. var descendants = this.getDescendants(false);
  16144. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16145. var descendant = descendants_1[_i];
  16146. var childMesh = descendant;
  16147. childMesh.computeWorldMatrix(true);
  16148. //make sure we have the needed params to get mix and max
  16149. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16150. continue;
  16151. }
  16152. var childBoundingInfo = childMesh.getBoundingInfo();
  16153. var boundingBox = childBoundingInfo.boundingBox;
  16154. var minBox = boundingBox.minimumWorld;
  16155. var maxBox = boundingBox.maximumWorld;
  16156. BABYLON.Tools.CheckExtends(minBox, min, max);
  16157. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16158. }
  16159. }
  16160. return {
  16161. min: min,
  16162. max: max
  16163. };
  16164. };
  16165. /**
  16166. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16167. * Returns the AbstractMesh.
  16168. */
  16169. AbstractMesh.prototype._updateBoundingInfo = function () {
  16170. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16171. this._boundingInfo.update(this.worldMatrixFromCache);
  16172. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16173. return this;
  16174. };
  16175. /**
  16176. * Update a mesh's children BoundingInfo objects only.
  16177. * Returns the AbstractMesh.
  16178. */
  16179. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16180. if (!this.subMeshes) {
  16181. return this;
  16182. }
  16183. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16184. var subMesh = this.subMeshes[subIndex];
  16185. if (!subMesh.IsGlobal) {
  16186. subMesh.updateBoundingInfo(matrix);
  16187. }
  16188. }
  16189. return this;
  16190. };
  16191. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16192. // Bounding info
  16193. this._updateBoundingInfo();
  16194. };
  16195. /**
  16196. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16197. * A mesh is in the frustum if its bounding box intersects the frustum.
  16198. * Boolean returned.
  16199. */
  16200. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16201. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16202. };
  16203. /**
  16204. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16205. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16206. * Boolean returned.
  16207. */
  16208. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16209. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16210. ;
  16211. };
  16212. /**
  16213. * True if the mesh intersects another mesh or a SolidParticle object.
  16214. * 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)
  16215. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16216. * Returns a boolean.
  16217. */
  16218. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16219. if (precise === void 0) { precise = false; }
  16220. if (!this._boundingInfo || !mesh._boundingInfo) {
  16221. return false;
  16222. }
  16223. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16224. return true;
  16225. }
  16226. if (includeDescendants) {
  16227. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16228. var child = _a[_i];
  16229. if (child.intersectsMesh(mesh, precise, true)) {
  16230. return true;
  16231. }
  16232. }
  16233. }
  16234. return false;
  16235. };
  16236. /**
  16237. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16238. * Returns a boolean.
  16239. */
  16240. AbstractMesh.prototype.intersectsPoint = function (point) {
  16241. if (!this._boundingInfo) {
  16242. return false;
  16243. }
  16244. return this._boundingInfo.intersectsPoint(point);
  16245. };
  16246. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16247. return this.physicsImpostor;
  16248. };
  16249. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16250. if (camera === void 0) { camera = null; }
  16251. if (!camera) {
  16252. camera = this.getScene().activeCamera;
  16253. }
  16254. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16255. };
  16256. /**
  16257. * Returns the distance from the mesh to the active camera.
  16258. * Returns a float.
  16259. */
  16260. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16261. if (camera === void 0) { camera = null; }
  16262. if (!camera) {
  16263. camera = this.getScene().activeCamera;
  16264. }
  16265. return this.absolutePosition.subtract(camera.position).length();
  16266. };
  16267. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16268. if (!this.physicsImpostor) {
  16269. return this;
  16270. }
  16271. this.physicsImpostor.applyImpulse(force, contactPoint);
  16272. return this;
  16273. };
  16274. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16275. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16276. return this;
  16277. }
  16278. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16279. mainPivot: pivot1,
  16280. connectedPivot: pivot2,
  16281. nativeParams: options
  16282. });
  16283. return this;
  16284. };
  16285. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16286. // Collisions
  16287. /**
  16288. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16289. * Default `false`.
  16290. */
  16291. get: function () {
  16292. return this._checkCollisions;
  16293. },
  16294. set: function (collisionEnabled) {
  16295. this._checkCollisions = collisionEnabled;
  16296. if (this.getScene().workerCollisions) {
  16297. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16298. }
  16299. },
  16300. enumerable: true,
  16301. configurable: true
  16302. });
  16303. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16304. /**
  16305. * Gets Collider object used to compute collisions (not physics)
  16306. */
  16307. get: function () {
  16308. return this._collider;
  16309. },
  16310. enumerable: true,
  16311. configurable: true
  16312. });
  16313. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16314. var globalPosition = this.getAbsolutePosition();
  16315. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16316. if (!this._collider) {
  16317. this._collider = new BABYLON.Collider();
  16318. }
  16319. this._collider._radius = this.ellipsoid;
  16320. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16321. return this;
  16322. };
  16323. // Submeshes octree
  16324. /**
  16325. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16326. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16327. * Returns an Octree of submeshes.
  16328. */
  16329. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16330. if (maxCapacity === void 0) { maxCapacity = 64; }
  16331. if (maxDepth === void 0) { maxDepth = 2; }
  16332. if (!this._submeshesOctree) {
  16333. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16334. }
  16335. this.computeWorldMatrix(true);
  16336. var boundingInfo = this.getBoundingInfo();
  16337. // Update octree
  16338. var bbox = boundingInfo.boundingBox;
  16339. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16340. return this._submeshesOctree;
  16341. };
  16342. // Collisions
  16343. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16344. this._generatePointsArray();
  16345. if (!this._positions) {
  16346. return this;
  16347. }
  16348. // Transformation
  16349. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16350. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16351. subMesh._lastColliderWorldVertices = [];
  16352. subMesh._trianglePlanes = [];
  16353. var start = subMesh.verticesStart;
  16354. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16355. for (var i = start; i < end; i++) {
  16356. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16357. }
  16358. }
  16359. // Collide
  16360. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16361. if (collider.collisionFound) {
  16362. collider.collidedMesh = this;
  16363. }
  16364. return this;
  16365. };
  16366. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16367. var subMeshes;
  16368. var len;
  16369. // Octrees
  16370. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16371. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16372. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16373. len = intersections.length;
  16374. subMeshes = intersections.data;
  16375. }
  16376. else {
  16377. subMeshes = this.subMeshes;
  16378. len = subMeshes.length;
  16379. }
  16380. for (var index = 0; index < len; index++) {
  16381. var subMesh = subMeshes[index];
  16382. // Bounding test
  16383. if (len > 1 && !subMesh._checkCollision(collider))
  16384. continue;
  16385. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16386. }
  16387. return this;
  16388. };
  16389. AbstractMesh.prototype._checkCollision = function (collider) {
  16390. // Bounding box test
  16391. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16392. return this;
  16393. // Transformation matrix
  16394. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16395. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16396. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16397. return this;
  16398. };
  16399. // Picking
  16400. AbstractMesh.prototype._generatePointsArray = function () {
  16401. return false;
  16402. };
  16403. /**
  16404. * Checks if the passed Ray intersects with the mesh.
  16405. * Returns an object PickingInfo.
  16406. */
  16407. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16408. var pickingInfo = new BABYLON.PickingInfo();
  16409. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16410. return pickingInfo;
  16411. }
  16412. if (!this._generatePointsArray()) {
  16413. return pickingInfo;
  16414. }
  16415. var intersectInfo = null;
  16416. // Octrees
  16417. var subMeshes;
  16418. var len;
  16419. if (this._submeshesOctree && this.useOctreeForPicking) {
  16420. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16421. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16422. len = intersections.length;
  16423. subMeshes = intersections.data;
  16424. }
  16425. else {
  16426. subMeshes = this.subMeshes;
  16427. len = subMeshes.length;
  16428. }
  16429. for (var index = 0; index < len; index++) {
  16430. var subMesh = subMeshes[index];
  16431. // Bounding test
  16432. if (len > 1 && !subMesh.canIntersects(ray))
  16433. continue;
  16434. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16435. if (currentIntersectInfo) {
  16436. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16437. intersectInfo = currentIntersectInfo;
  16438. intersectInfo.subMeshId = index;
  16439. if (fastCheck) {
  16440. break;
  16441. }
  16442. }
  16443. }
  16444. }
  16445. if (intersectInfo) {
  16446. // Get picked point
  16447. var world = this.getWorldMatrix();
  16448. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  16449. var direction = ray.direction.clone();
  16450. direction = direction.scale(intersectInfo.distance);
  16451. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  16452. var pickedPoint = worldOrigin.add(worldDirection);
  16453. // Return result
  16454. pickingInfo.hit = true;
  16455. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  16456. pickingInfo.pickedPoint = pickedPoint;
  16457. pickingInfo.pickedMesh = this;
  16458. pickingInfo.bu = intersectInfo.bu || 0;
  16459. pickingInfo.bv = intersectInfo.bv || 0;
  16460. pickingInfo.faceId = intersectInfo.faceId;
  16461. pickingInfo.subMeshId = intersectInfo.subMeshId;
  16462. return pickingInfo;
  16463. }
  16464. return pickingInfo;
  16465. };
  16466. /**
  16467. * Clones the mesh, used by the class Mesh.
  16468. * Just returns `null` for an AbstractMesh.
  16469. */
  16470. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16471. return null;
  16472. };
  16473. /**
  16474. * Disposes all the mesh submeshes.
  16475. * Returns the AbstractMesh.
  16476. */
  16477. AbstractMesh.prototype.releaseSubMeshes = function () {
  16478. if (this.subMeshes) {
  16479. while (this.subMeshes.length) {
  16480. this.subMeshes[0].dispose();
  16481. }
  16482. }
  16483. else {
  16484. this.subMeshes = new Array();
  16485. }
  16486. return this;
  16487. };
  16488. /**
  16489. * Disposes the AbstractMesh.
  16490. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16491. * Returns nothing.
  16492. */
  16493. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16494. var _this = this;
  16495. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16496. var index;
  16497. // Action manager
  16498. if (this.actionManager !== undefined && this.actionManager !== null) {
  16499. this.actionManager.dispose();
  16500. this.actionManager = null;
  16501. }
  16502. // Skeleton
  16503. this.skeleton = null;
  16504. // Physics
  16505. if (this.physicsImpostor) {
  16506. this.physicsImpostor.dispose();
  16507. }
  16508. // Intersections in progress
  16509. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  16510. var other = this._intersectionsInProgress[index];
  16511. var pos = other._intersectionsInProgress.indexOf(this);
  16512. other._intersectionsInProgress.splice(pos, 1);
  16513. }
  16514. this._intersectionsInProgress = [];
  16515. // Lights
  16516. var lights = this.getScene().lights;
  16517. lights.forEach(function (light) {
  16518. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  16519. if (meshIndex !== -1) {
  16520. light.includedOnlyMeshes.splice(meshIndex, 1);
  16521. }
  16522. meshIndex = light.excludedMeshes.indexOf(_this);
  16523. if (meshIndex !== -1) {
  16524. light.excludedMeshes.splice(meshIndex, 1);
  16525. }
  16526. // Shadow generators
  16527. var generator = light.getShadowGenerator();
  16528. if (generator) {
  16529. var shadowMap = generator.getShadowMap();
  16530. if (shadowMap && shadowMap.renderList) {
  16531. meshIndex = shadowMap.renderList.indexOf(_this);
  16532. if (meshIndex !== -1) {
  16533. shadowMap.renderList.splice(meshIndex, 1);
  16534. }
  16535. }
  16536. }
  16537. });
  16538. // Edges
  16539. if (this._edgesRenderer) {
  16540. this._edgesRenderer.dispose();
  16541. this._edgesRenderer = null;
  16542. }
  16543. // SubMeshes
  16544. if (this.getClassName() !== "InstancedMesh") {
  16545. this.releaseSubMeshes();
  16546. }
  16547. // Octree
  16548. var sceneOctree = this.getScene().selectionOctree;
  16549. if (sceneOctree !== undefined && sceneOctree !== null) {
  16550. var index = sceneOctree.dynamicContent.indexOf(this);
  16551. if (index !== -1) {
  16552. sceneOctree.dynamicContent.splice(index, 1);
  16553. }
  16554. }
  16555. // Query
  16556. var engine = this.getScene().getEngine();
  16557. if (this._occlusionQuery) {
  16558. this._isOcclusionQueryInProgress = false;
  16559. engine.deleteQuery(this._occlusionQuery);
  16560. this._occlusionQuery = null;
  16561. }
  16562. // Engine
  16563. engine.wipeCaches();
  16564. // Remove from scene
  16565. this.getScene().removeMesh(this);
  16566. if (disposeMaterialAndTextures) {
  16567. if (this.material) {
  16568. this.material.dispose(false, true);
  16569. }
  16570. }
  16571. if (!doNotRecurse) {
  16572. // Particles
  16573. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  16574. if (this.getScene().particleSystems[index].emitter === this) {
  16575. this.getScene().particleSystems[index].dispose();
  16576. index--;
  16577. }
  16578. }
  16579. }
  16580. // facet data
  16581. if (this._facetDataEnabled) {
  16582. this.disableFacetData();
  16583. }
  16584. this.onAfterWorldMatrixUpdateObservable.clear();
  16585. this.onCollideObservable.clear();
  16586. this.onCollisionPositionChangeObservable.clear();
  16587. this._isDisposed = true;
  16588. _super.prototype.dispose.call(this, doNotRecurse);
  16589. };
  16590. /**
  16591. * Adds the passed mesh as a child to the current mesh.
  16592. * Returns the AbstractMesh.
  16593. */
  16594. AbstractMesh.prototype.addChild = function (mesh) {
  16595. mesh.setParent(this);
  16596. return this;
  16597. };
  16598. /**
  16599. * Removes the passed mesh from the current mesh children list.
  16600. * Returns the AbstractMesh.
  16601. */
  16602. AbstractMesh.prototype.removeChild = function (mesh) {
  16603. mesh.setParent(null);
  16604. return this;
  16605. };
  16606. // Facet data
  16607. /**
  16608. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  16609. * Returns the AbstractMesh.
  16610. */
  16611. AbstractMesh.prototype._initFacetData = function () {
  16612. if (!this._facetNormals) {
  16613. this._facetNormals = new Array();
  16614. }
  16615. if (!this._facetPositions) {
  16616. this._facetPositions = new Array();
  16617. }
  16618. if (!this._facetPartitioning) {
  16619. this._facetPartitioning = new Array();
  16620. }
  16621. this._facetNb = (this.getIndices().length / 3) | 0;
  16622. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  16623. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  16624. for (var f = 0; f < this._facetNb; f++) {
  16625. this._facetNormals[f] = BABYLON.Vector3.Zero();
  16626. this._facetPositions[f] = BABYLON.Vector3.Zero();
  16627. }
  16628. this._facetDataEnabled = true;
  16629. return this;
  16630. };
  16631. /**
  16632. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  16633. * This method can be called within the render loop.
  16634. * 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.
  16635. * Returns the AbstractMesh.
  16636. */
  16637. AbstractMesh.prototype.updateFacetData = function () {
  16638. if (!this._facetDataEnabled) {
  16639. this._initFacetData();
  16640. }
  16641. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16642. var indices = this.getIndices();
  16643. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16644. var bInfo = this.getBoundingInfo();
  16645. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  16646. // init arrays, matrix and sort function on first call
  16647. this._facetDepthSortEnabled = true;
  16648. if (indices instanceof Uint16Array) {
  16649. this._depthSortedIndices = new Uint16Array(indices);
  16650. }
  16651. else if (indices instanceof Uint32Array) {
  16652. this._depthSortedIndices = new Uint32Array(indices);
  16653. }
  16654. else {
  16655. var needs32bits = false;
  16656. for (var i = 0; i < indices.length; i++) {
  16657. if (indices[i] > 65535) {
  16658. needs32bits = true;
  16659. break;
  16660. }
  16661. }
  16662. if (needs32bits) {
  16663. this._depthSortedIndices = new Uint32Array(indices);
  16664. }
  16665. else {
  16666. this._depthSortedIndices = new Uint16Array(indices);
  16667. }
  16668. }
  16669. this._facetDepthSortFunction = function (f1, f2) {
  16670. return (f2.sqDistance - f1.sqDistance);
  16671. };
  16672. if (!this._facetDepthSortFrom) {
  16673. var camera = this.getScene().activeCamera;
  16674. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  16675. }
  16676. this._depthSortedFacets = [];
  16677. for (var f = 0; f < this._facetNb; f++) {
  16678. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  16679. this._depthSortedFacets.push(depthSortedFacet);
  16680. }
  16681. this._invertedMatrix = BABYLON.Matrix.Identity();
  16682. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  16683. }
  16684. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  16685. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  16686. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  16687. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  16688. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  16689. this._subDiv.max = this._partitioningSubdivisions;
  16690. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  16691. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  16692. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  16693. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  16694. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  16695. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  16696. // set the parameters for ComputeNormals()
  16697. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  16698. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  16699. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  16700. this._facetParameters.bInfo = bInfo;
  16701. this._facetParameters.bbSize = this._bbSize;
  16702. this._facetParameters.subDiv = this._subDiv;
  16703. this._facetParameters.ratio = this.partitioningBBoxRatio;
  16704. this._facetParameters.depthSort = this._facetDepthSort;
  16705. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16706. this.computeWorldMatrix(true);
  16707. this._worldMatrix.invertToRef(this._invertedMatrix);
  16708. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  16709. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  16710. }
  16711. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  16712. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  16713. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16714. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  16715. var l = (this._depthSortedIndices.length / 3) | 0;
  16716. for (var f = 0; f < l; f++) {
  16717. var sind = this._depthSortedFacets[f].ind;
  16718. this._depthSortedIndices[f * 3] = indices[sind];
  16719. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  16720. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  16721. }
  16722. this.updateIndices(this._depthSortedIndices);
  16723. }
  16724. return this;
  16725. };
  16726. /**
  16727. * Returns the facetLocalNormals array.
  16728. * The normals are expressed in the mesh local space.
  16729. */
  16730. AbstractMesh.prototype.getFacetLocalNormals = function () {
  16731. if (!this._facetNormals) {
  16732. this.updateFacetData();
  16733. }
  16734. return this._facetNormals;
  16735. };
  16736. /**
  16737. * Returns the facetLocalPositions array.
  16738. * The facet positions are expressed in the mesh local space.
  16739. */
  16740. AbstractMesh.prototype.getFacetLocalPositions = function () {
  16741. if (!this._facetPositions) {
  16742. this.updateFacetData();
  16743. }
  16744. return this._facetPositions;
  16745. };
  16746. /**
  16747. * Returns the facetLocalPartioning array.
  16748. */
  16749. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  16750. if (!this._facetPartitioning) {
  16751. this.updateFacetData();
  16752. }
  16753. return this._facetPartitioning;
  16754. };
  16755. /**
  16756. * Returns the i-th facet position in the world system.
  16757. * This method allocates a new Vector3 per call.
  16758. */
  16759. AbstractMesh.prototype.getFacetPosition = function (i) {
  16760. var pos = BABYLON.Vector3.Zero();
  16761. this.getFacetPositionToRef(i, pos);
  16762. return pos;
  16763. };
  16764. /**
  16765. * Sets the reference Vector3 with the i-th facet position in the world system.
  16766. * Returns the AbstractMesh.
  16767. */
  16768. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  16769. var localPos = (this.getFacetLocalPositions())[i];
  16770. var world = this.getWorldMatrix();
  16771. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  16772. return this;
  16773. };
  16774. /**
  16775. * Returns the i-th facet normal in the world system.
  16776. * This method allocates a new Vector3 per call.
  16777. */
  16778. AbstractMesh.prototype.getFacetNormal = function (i) {
  16779. var norm = BABYLON.Vector3.Zero();
  16780. this.getFacetNormalToRef(i, norm);
  16781. return norm;
  16782. };
  16783. /**
  16784. * Sets the reference Vector3 with the i-th facet normal in the world system.
  16785. * Returns the AbstractMesh.
  16786. */
  16787. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  16788. var localNorm = (this.getFacetLocalNormals())[i];
  16789. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  16790. return this;
  16791. };
  16792. /**
  16793. * 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).
  16794. */
  16795. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  16796. var bInfo = this.getBoundingInfo();
  16797. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  16798. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  16799. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  16800. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  16801. return null;
  16802. }
  16803. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  16804. };
  16805. /**
  16806. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  16807. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  16808. * 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.
  16809. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16810. * 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.
  16811. */
  16812. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  16813. if (checkFace === void 0) { checkFace = false; }
  16814. if (facing === void 0) { facing = true; }
  16815. var world = this.getWorldMatrix();
  16816. var invMat = BABYLON.Tmp.Matrix[5];
  16817. world.invertToRef(invMat);
  16818. var invVect = BABYLON.Tmp.Vector3[8];
  16819. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  16820. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  16821. if (projected) {
  16822. // tranform the local computed projected vector to world coordinates
  16823. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  16824. }
  16825. return closest;
  16826. };
  16827. /**
  16828. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  16829. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  16830. * 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.
  16831. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16832. * 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.
  16833. */
  16834. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  16835. if (checkFace === void 0) { checkFace = false; }
  16836. if (facing === void 0) { facing = true; }
  16837. var closest = null;
  16838. var tmpx = 0.0;
  16839. var tmpy = 0.0;
  16840. var tmpz = 0.0;
  16841. var d = 0.0; // tmp dot facet normal * facet position
  16842. var t0 = 0.0;
  16843. var projx = 0.0;
  16844. var projy = 0.0;
  16845. var projz = 0.0;
  16846. // Get all the facets in the same partitioning block than (x, y, z)
  16847. var facetPositions = this.getFacetLocalPositions();
  16848. var facetNormals = this.getFacetLocalNormals();
  16849. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  16850. if (!facetsInBlock) {
  16851. return null;
  16852. }
  16853. // Get the closest facet to (x, y, z)
  16854. var shortest = Number.MAX_VALUE; // init distance vars
  16855. var tmpDistance = shortest;
  16856. var fib; // current facet in the block
  16857. var norm; // current facet normal
  16858. var p0; // current facet barycenter position
  16859. // loop on all the facets in the current partitioning block
  16860. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  16861. fib = facetsInBlock[idx];
  16862. norm = facetNormals[fib];
  16863. p0 = facetPositions[fib];
  16864. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  16865. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  16866. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  16867. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  16868. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  16869. projx = x + norm.x * t0;
  16870. projy = y + norm.y * t0;
  16871. projz = z + norm.z * t0;
  16872. tmpx = projx - x;
  16873. tmpy = projy - y;
  16874. tmpz = projz - z;
  16875. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  16876. if (tmpDistance < shortest) {
  16877. shortest = tmpDistance;
  16878. closest = fib;
  16879. if (projected) {
  16880. projected.x = projx;
  16881. projected.y = projy;
  16882. projected.z = projz;
  16883. }
  16884. }
  16885. }
  16886. }
  16887. return closest;
  16888. };
  16889. /**
  16890. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  16891. */
  16892. AbstractMesh.prototype.getFacetDataParameters = function () {
  16893. return this._facetParameters;
  16894. };
  16895. /**
  16896. * Disables the feature FacetData and frees the related memory.
  16897. * Returns the AbstractMesh.
  16898. */
  16899. AbstractMesh.prototype.disableFacetData = function () {
  16900. if (this._facetDataEnabled) {
  16901. this._facetDataEnabled = false;
  16902. this._facetPositions = new Array();
  16903. this._facetNormals = new Array();
  16904. this._facetPartitioning = new Array();
  16905. this._facetParameters = null;
  16906. this._depthSortedIndices = new Uint32Array(0);
  16907. }
  16908. return this;
  16909. };
  16910. /**
  16911. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  16912. * Returns the mesh.
  16913. */
  16914. AbstractMesh.prototype.updateIndices = function (indices) {
  16915. return this;
  16916. };
  16917. /**
  16918. * The mesh Geometry. Actually used by the Mesh object.
  16919. * Returns a blank geometry object.
  16920. */
  16921. /**
  16922. * Creates new normals data for the mesh.
  16923. * @param updatable.
  16924. */
  16925. AbstractMesh.prototype.createNormals = function (updatable) {
  16926. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16927. var indices = this.getIndices();
  16928. var normals;
  16929. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16930. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16931. }
  16932. else {
  16933. normals = [];
  16934. }
  16935. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  16936. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  16937. };
  16938. /**
  16939. * Align the mesh with a normal.
  16940. * Returns the mesh.
  16941. */
  16942. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  16943. if (!upDirection) {
  16944. upDirection = BABYLON.Axis.Y;
  16945. }
  16946. var axisX = BABYLON.Tmp.Vector3[0];
  16947. var axisZ = BABYLON.Tmp.Vector3[1];
  16948. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  16949. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  16950. if (this.rotationQuaternion) {
  16951. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  16952. }
  16953. else {
  16954. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  16955. }
  16956. return this;
  16957. };
  16958. AbstractMesh.prototype.checkOcclusionQuery = function () {
  16959. var engine = this.getEngine();
  16960. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  16961. this._isOccluded = false;
  16962. return;
  16963. }
  16964. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  16965. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  16966. if (isOcclusionQueryAvailable) {
  16967. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  16968. this._isOcclusionQueryInProgress = false;
  16969. this._occlusionInternalRetryCounter = 0;
  16970. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  16971. }
  16972. else {
  16973. this._occlusionInternalRetryCounter++;
  16974. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  16975. this._isOcclusionQueryInProgress = false;
  16976. this._occlusionInternalRetryCounter = 0;
  16977. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  16978. // if strict continue the last state of the object.
  16979. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  16980. }
  16981. else {
  16982. return;
  16983. }
  16984. }
  16985. }
  16986. var scene = this.getScene();
  16987. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  16988. if (!this._occlusionQuery) {
  16989. this._occlusionQuery = engine.createQuery();
  16990. }
  16991. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  16992. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  16993. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  16994. this._isOcclusionQueryInProgress = true;
  16995. };
  16996. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  16997. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  16998. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  16999. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  17000. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  17001. return AbstractMesh;
  17002. }(BABYLON.TransformNode));
  17003. BABYLON.AbstractMesh = AbstractMesh;
  17004. })(BABYLON || (BABYLON = {}));
  17005. //# sourceMappingURL=babylon.abstractMesh.js.map
  17006. var BABYLON;
  17007. (function (BABYLON) {
  17008. var Light = /** @class */ (function (_super) {
  17009. __extends(Light, _super);
  17010. /**
  17011. * Creates a Light object in the scene.
  17012. * Documentation : http://doc.babylonjs.com/tutorials/lights
  17013. */
  17014. function Light(name, scene) {
  17015. var _this = _super.call(this, name, scene) || this;
  17016. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17017. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17018. _this.intensity = 1.0;
  17019. _this.range = Number.MAX_VALUE;
  17020. /**
  17021. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17022. * of light.
  17023. */
  17024. _this._photometricScale = 1.0;
  17025. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17026. _this._radius = 0.00001;
  17027. _this.renderPriority = 0;
  17028. /**
  17029. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17030. * the current shadow generator.
  17031. */
  17032. _this.shadowEnabled = true;
  17033. _this._excludeWithLayerMask = 0;
  17034. _this._includeOnlyWithLayerMask = 0;
  17035. _this._lightmapMode = 0;
  17036. _this._excludedMeshesIds = new Array();
  17037. _this._includedOnlyMeshesIds = new Array();
  17038. _this.getScene().addLight(_this);
  17039. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17040. _this._buildUniformLayout();
  17041. _this.includedOnlyMeshes = new Array();
  17042. _this.excludedMeshes = new Array();
  17043. _this._resyncMeshes();
  17044. return _this;
  17045. }
  17046. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17047. /**
  17048. * If every light affecting the material is in this lightmapMode,
  17049. * material.lightmapTexture adds or multiplies
  17050. * (depends on material.useLightmapAsShadowmap)
  17051. * after every other light calculations.
  17052. */
  17053. get: function () {
  17054. return Light._LIGHTMAP_DEFAULT;
  17055. },
  17056. enumerable: true,
  17057. configurable: true
  17058. });
  17059. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17060. /**
  17061. * material.lightmapTexture as only diffuse lighting from this light
  17062. * adds only specular lighting from this light
  17063. * adds dynamic shadows
  17064. */
  17065. get: function () {
  17066. return Light._LIGHTMAP_SPECULAR;
  17067. },
  17068. enumerable: true,
  17069. configurable: true
  17070. });
  17071. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17072. /**
  17073. * material.lightmapTexture as only lighting
  17074. * no light calculation from this light
  17075. * only adds dynamic shadows from this light
  17076. */
  17077. get: function () {
  17078. return Light._LIGHTMAP_SHADOWSONLY;
  17079. },
  17080. enumerable: true,
  17081. configurable: true
  17082. });
  17083. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17084. /**
  17085. * Each light type uses the default quantity according to its type:
  17086. * point/spot lights use luminous intensity
  17087. * directional lights use illuminance
  17088. */
  17089. get: function () {
  17090. return Light._INTENSITYMODE_AUTOMATIC;
  17091. },
  17092. enumerable: true,
  17093. configurable: true
  17094. });
  17095. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17096. /**
  17097. * lumen (lm)
  17098. */
  17099. get: function () {
  17100. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17101. },
  17102. enumerable: true,
  17103. configurable: true
  17104. });
  17105. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17106. /**
  17107. * candela (lm/sr)
  17108. */
  17109. get: function () {
  17110. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17111. },
  17112. enumerable: true,
  17113. configurable: true
  17114. });
  17115. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17116. /**
  17117. * lux (lm/m^2)
  17118. */
  17119. get: function () {
  17120. return Light._INTENSITYMODE_ILLUMINANCE;
  17121. },
  17122. enumerable: true,
  17123. configurable: true
  17124. });
  17125. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17126. /**
  17127. * nit (cd/m^2)
  17128. */
  17129. get: function () {
  17130. return Light._INTENSITYMODE_LUMINANCE;
  17131. },
  17132. enumerable: true,
  17133. configurable: true
  17134. });
  17135. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17136. /**
  17137. * Light type const id of the point light.
  17138. */
  17139. get: function () {
  17140. return Light._LIGHTTYPEID_POINTLIGHT;
  17141. },
  17142. enumerable: true,
  17143. configurable: true
  17144. });
  17145. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17146. /**
  17147. * Light type const id of the directional light.
  17148. */
  17149. get: function () {
  17150. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17151. },
  17152. enumerable: true,
  17153. configurable: true
  17154. });
  17155. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17156. /**
  17157. * Light type const id of the spot light.
  17158. */
  17159. get: function () {
  17160. return Light._LIGHTTYPEID_SPOTLIGHT;
  17161. },
  17162. enumerable: true,
  17163. configurable: true
  17164. });
  17165. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17166. /**
  17167. * Light type const id of the hemispheric light.
  17168. */
  17169. get: function () {
  17170. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17171. },
  17172. enumerable: true,
  17173. configurable: true
  17174. });
  17175. Object.defineProperty(Light.prototype, "intensityMode", {
  17176. /**
  17177. * Gets the photometric scale used to interpret the intensity.
  17178. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17179. */
  17180. get: function () {
  17181. return this._intensityMode;
  17182. },
  17183. /**
  17184. * Sets the photometric scale used to interpret the intensity.
  17185. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17186. */
  17187. set: function (value) {
  17188. this._intensityMode = value;
  17189. this._computePhotometricScale();
  17190. },
  17191. enumerable: true,
  17192. configurable: true
  17193. });
  17194. ;
  17195. ;
  17196. Object.defineProperty(Light.prototype, "radius", {
  17197. /**
  17198. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17199. */
  17200. get: function () {
  17201. return this._radius;
  17202. },
  17203. /**
  17204. * sets the light radius used by PBR Materials to simulate soft area lights.
  17205. */
  17206. set: function (value) {
  17207. this._radius = value;
  17208. this._computePhotometricScale();
  17209. },
  17210. enumerable: true,
  17211. configurable: true
  17212. });
  17213. ;
  17214. ;
  17215. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17216. get: function () {
  17217. return this._includedOnlyMeshes;
  17218. },
  17219. set: function (value) {
  17220. this._includedOnlyMeshes = value;
  17221. this._hookArrayForIncludedOnly(value);
  17222. },
  17223. enumerable: true,
  17224. configurable: true
  17225. });
  17226. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17227. get: function () {
  17228. return this._excludedMeshes;
  17229. },
  17230. set: function (value) {
  17231. this._excludedMeshes = value;
  17232. this._hookArrayForExcluded(value);
  17233. },
  17234. enumerable: true,
  17235. configurable: true
  17236. });
  17237. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17238. get: function () {
  17239. return this._excludeWithLayerMask;
  17240. },
  17241. set: function (value) {
  17242. this._excludeWithLayerMask = value;
  17243. this._resyncMeshes();
  17244. },
  17245. enumerable: true,
  17246. configurable: true
  17247. });
  17248. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17249. get: function () {
  17250. return this._includeOnlyWithLayerMask;
  17251. },
  17252. set: function (value) {
  17253. this._includeOnlyWithLayerMask = value;
  17254. this._resyncMeshes();
  17255. },
  17256. enumerable: true,
  17257. configurable: true
  17258. });
  17259. Object.defineProperty(Light.prototype, "lightmapMode", {
  17260. get: function () {
  17261. return this._lightmapMode;
  17262. },
  17263. set: function (value) {
  17264. if (this._lightmapMode === value) {
  17265. return;
  17266. }
  17267. this._lightmapMode = value;
  17268. this._markMeshesAsLightDirty();
  17269. },
  17270. enumerable: true,
  17271. configurable: true
  17272. });
  17273. Light.prototype._buildUniformLayout = function () {
  17274. // Overridden
  17275. };
  17276. /**
  17277. * Returns the string "Light".
  17278. */
  17279. Light.prototype.getClassName = function () {
  17280. return "Light";
  17281. };
  17282. /**
  17283. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17284. */
  17285. Light.prototype.toString = function (fullDetails) {
  17286. var ret = "Name: " + this.name;
  17287. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17288. if (this.animations) {
  17289. for (var i = 0; i < this.animations.length; i++) {
  17290. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17291. }
  17292. }
  17293. if (fullDetails) {
  17294. }
  17295. return ret;
  17296. };
  17297. /**
  17298. * Set the enabled state of this node.
  17299. * @param {boolean} value - the new enabled state
  17300. * @see isEnabled
  17301. */
  17302. Light.prototype.setEnabled = function (value) {
  17303. _super.prototype.setEnabled.call(this, value);
  17304. this._resyncMeshes();
  17305. };
  17306. /**
  17307. * Returns the Light associated shadow generator.
  17308. */
  17309. Light.prototype.getShadowGenerator = function () {
  17310. return this._shadowGenerator;
  17311. };
  17312. /**
  17313. * Returns a Vector3, the absolute light position in the World.
  17314. */
  17315. Light.prototype.getAbsolutePosition = function () {
  17316. return BABYLON.Vector3.Zero();
  17317. };
  17318. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17319. };
  17320. Light.prototype._getWorldMatrix = function () {
  17321. return BABYLON.Matrix.Identity();
  17322. };
  17323. /**
  17324. * Boolean : True if the light will affect the passed mesh.
  17325. */
  17326. Light.prototype.canAffectMesh = function (mesh) {
  17327. if (!mesh) {
  17328. return true;
  17329. }
  17330. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17331. return false;
  17332. }
  17333. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17334. return false;
  17335. }
  17336. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17337. return false;
  17338. }
  17339. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17340. return false;
  17341. }
  17342. return true;
  17343. };
  17344. /**
  17345. * Returns the light World matrix.
  17346. */
  17347. Light.prototype.getWorldMatrix = function () {
  17348. this._currentRenderId = this.getScene().getRenderId();
  17349. var worldMatrix = this._getWorldMatrix();
  17350. if (this.parent && this.parent.getWorldMatrix) {
  17351. if (!this._parentedWorldMatrix) {
  17352. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17353. }
  17354. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17355. this._markSyncedWithParent();
  17356. return this._parentedWorldMatrix;
  17357. }
  17358. return worldMatrix;
  17359. };
  17360. /**
  17361. * Sort function to order lights for rendering.
  17362. * @param a First Light object to compare to second.
  17363. * @param b Second Light object to compare first.
  17364. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17365. */
  17366. Light.compareLightsPriority = function (a, b) {
  17367. //shadow-casting lights have priority over non-shadow-casting lights
  17368. //the renderPrioirty is a secondary sort criterion
  17369. if (a.shadowEnabled !== b.shadowEnabled) {
  17370. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17371. }
  17372. return b.renderPriority - a.renderPriority;
  17373. };
  17374. /**
  17375. * Disposes the light.
  17376. */
  17377. Light.prototype.dispose = function () {
  17378. if (this._shadowGenerator) {
  17379. this._shadowGenerator.dispose();
  17380. this._shadowGenerator = null;
  17381. }
  17382. // Animations
  17383. this.getScene().stopAnimation(this);
  17384. this._uniformBuffer.dispose();
  17385. // Remove from scene
  17386. this.getScene().removeLight(this);
  17387. _super.prototype.dispose.call(this);
  17388. };
  17389. /**
  17390. * Returns the light type ID (integer).
  17391. */
  17392. Light.prototype.getTypeID = function () {
  17393. return 0;
  17394. };
  17395. /**
  17396. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17397. */
  17398. Light.prototype.getScaledIntensity = function () {
  17399. return this._photometricScale * this.intensity;
  17400. };
  17401. /**
  17402. * Returns a new Light object, named "name", from the current one.
  17403. */
  17404. Light.prototype.clone = function (name) {
  17405. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17406. if (!constructor) {
  17407. return null;
  17408. }
  17409. return BABYLON.SerializationHelper.Clone(constructor, this);
  17410. };
  17411. /**
  17412. * Serializes the current light into a Serialization object.
  17413. * Returns the serialized object.
  17414. */
  17415. Light.prototype.serialize = function () {
  17416. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17417. // Type
  17418. serializationObject.type = this.getTypeID();
  17419. // Parent
  17420. if (this.parent) {
  17421. serializationObject.parentId = this.parent.id;
  17422. }
  17423. // Inclusion / exclusions
  17424. if (this.excludedMeshes.length > 0) {
  17425. serializationObject.excludedMeshesIds = [];
  17426. this.excludedMeshes.forEach(function (mesh) {
  17427. serializationObject.excludedMeshesIds.push(mesh.id);
  17428. });
  17429. }
  17430. if (this.includedOnlyMeshes.length > 0) {
  17431. serializationObject.includedOnlyMeshesIds = [];
  17432. this.includedOnlyMeshes.forEach(function (mesh) {
  17433. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17434. });
  17435. }
  17436. // Animations
  17437. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17438. serializationObject.ranges = this.serializeAnimationRanges();
  17439. return serializationObject;
  17440. };
  17441. /**
  17442. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  17443. * This new light is named "name" and added to the passed scene.
  17444. */
  17445. Light.GetConstructorFromName = function (type, name, scene) {
  17446. switch (type) {
  17447. case 0:
  17448. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  17449. case 1:
  17450. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  17451. case 2:
  17452. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  17453. case 3:
  17454. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  17455. }
  17456. return null;
  17457. };
  17458. /**
  17459. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  17460. */
  17461. Light.Parse = function (parsedLight, scene) {
  17462. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  17463. if (!constructor) {
  17464. return null;
  17465. }
  17466. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  17467. // Inclusion / exclusions
  17468. if (parsedLight.excludedMeshesIds) {
  17469. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17470. }
  17471. if (parsedLight.includedOnlyMeshesIds) {
  17472. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17473. }
  17474. // Parent
  17475. if (parsedLight.parentId) {
  17476. light._waitingParentId = parsedLight.parentId;
  17477. }
  17478. // Animations
  17479. if (parsedLight.animations) {
  17480. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17481. var parsedAnimation = parsedLight.animations[animationIndex];
  17482. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17483. }
  17484. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  17485. }
  17486. if (parsedLight.autoAnimate) {
  17487. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  17488. }
  17489. return light;
  17490. };
  17491. Light.prototype._hookArrayForExcluded = function (array) {
  17492. var _this = this;
  17493. var oldPush = array.push;
  17494. array.push = function () {
  17495. var items = [];
  17496. for (var _i = 0; _i < arguments.length; _i++) {
  17497. items[_i] = arguments[_i];
  17498. }
  17499. var result = oldPush.apply(array, items);
  17500. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  17501. var item = items_1[_a];
  17502. item._resyncLighSource(_this);
  17503. }
  17504. return result;
  17505. };
  17506. var oldSplice = array.splice;
  17507. array.splice = function (index, deleteCount) {
  17508. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17509. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  17510. var item = deleted_1[_i];
  17511. item._resyncLighSource(_this);
  17512. }
  17513. return deleted;
  17514. };
  17515. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  17516. var item = array_1[_i];
  17517. item._resyncLighSource(this);
  17518. }
  17519. };
  17520. Light.prototype._hookArrayForIncludedOnly = function (array) {
  17521. var _this = this;
  17522. var oldPush = array.push;
  17523. array.push = function () {
  17524. var items = [];
  17525. for (var _i = 0; _i < arguments.length; _i++) {
  17526. items[_i] = arguments[_i];
  17527. }
  17528. var result = oldPush.apply(array, items);
  17529. _this._resyncMeshes();
  17530. return result;
  17531. };
  17532. var oldSplice = array.splice;
  17533. array.splice = function (index, deleteCount) {
  17534. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17535. _this._resyncMeshes();
  17536. return deleted;
  17537. };
  17538. this._resyncMeshes();
  17539. };
  17540. Light.prototype._resyncMeshes = function () {
  17541. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17542. var mesh = _a[_i];
  17543. mesh._resyncLighSource(this);
  17544. }
  17545. };
  17546. Light.prototype._markMeshesAsLightDirty = function () {
  17547. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17548. var mesh = _a[_i];
  17549. if (mesh._lightSources.indexOf(this) !== -1) {
  17550. mesh._markSubMeshesAsLightDirty();
  17551. }
  17552. }
  17553. };
  17554. /**
  17555. * Recomputes the cached photometric scale if needed.
  17556. */
  17557. Light.prototype._computePhotometricScale = function () {
  17558. this._photometricScale = this._getPhotometricScale();
  17559. this.getScene().resetCachedMaterial();
  17560. };
  17561. /**
  17562. * Returns the Photometric Scale according to the light type and intensity mode.
  17563. */
  17564. Light.prototype._getPhotometricScale = function () {
  17565. var photometricScale = 0.0;
  17566. var lightTypeID = this.getTypeID();
  17567. //get photometric mode
  17568. var photometricMode = this.intensityMode;
  17569. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  17570. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  17571. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  17572. }
  17573. else {
  17574. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  17575. }
  17576. }
  17577. //compute photometric scale
  17578. switch (lightTypeID) {
  17579. case Light.LIGHTTYPEID_POINTLIGHT:
  17580. case Light.LIGHTTYPEID_SPOTLIGHT:
  17581. switch (photometricMode) {
  17582. case Light.INTENSITYMODE_LUMINOUSPOWER:
  17583. photometricScale = 1.0 / (4.0 * Math.PI);
  17584. break;
  17585. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  17586. photometricScale = 1.0;
  17587. break;
  17588. case Light.INTENSITYMODE_LUMINANCE:
  17589. photometricScale = this.radius * this.radius;
  17590. break;
  17591. }
  17592. break;
  17593. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  17594. switch (photometricMode) {
  17595. case Light.INTENSITYMODE_ILLUMINANCE:
  17596. photometricScale = 1.0;
  17597. break;
  17598. case Light.INTENSITYMODE_LUMINANCE:
  17599. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  17600. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  17601. var apexAngleRadians = this.radius;
  17602. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  17603. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  17604. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  17605. photometricScale = solidAngle;
  17606. break;
  17607. }
  17608. break;
  17609. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  17610. // No fall off in hemisperic light.
  17611. photometricScale = 1.0;
  17612. break;
  17613. }
  17614. return photometricScale;
  17615. };
  17616. Light.prototype._reorderLightsInScene = function () {
  17617. var scene = this.getScene();
  17618. if (this._renderPriority != 0) {
  17619. scene.requireLightSorting = true;
  17620. }
  17621. this.getScene().sortLightsByPriority();
  17622. };
  17623. //lightmapMode Consts
  17624. Light._LIGHTMAP_DEFAULT = 0;
  17625. Light._LIGHTMAP_SPECULAR = 1;
  17626. Light._LIGHTMAP_SHADOWSONLY = 2;
  17627. // Intensity Mode Consts
  17628. Light._INTENSITYMODE_AUTOMATIC = 0;
  17629. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  17630. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  17631. Light._INTENSITYMODE_ILLUMINANCE = 3;
  17632. Light._INTENSITYMODE_LUMINANCE = 4;
  17633. // Light types ids const.
  17634. Light._LIGHTTYPEID_POINTLIGHT = 0;
  17635. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  17636. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  17637. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  17638. __decorate([
  17639. BABYLON.serializeAsColor3()
  17640. ], Light.prototype, "diffuse", void 0);
  17641. __decorate([
  17642. BABYLON.serializeAsColor3()
  17643. ], Light.prototype, "specular", void 0);
  17644. __decorate([
  17645. BABYLON.serialize()
  17646. ], Light.prototype, "intensity", void 0);
  17647. __decorate([
  17648. BABYLON.serialize()
  17649. ], Light.prototype, "range", void 0);
  17650. __decorate([
  17651. BABYLON.serialize()
  17652. ], Light.prototype, "intensityMode", null);
  17653. __decorate([
  17654. BABYLON.serialize()
  17655. ], Light.prototype, "radius", null);
  17656. __decorate([
  17657. BABYLON.serialize()
  17658. ], Light.prototype, "_renderPriority", void 0);
  17659. __decorate([
  17660. BABYLON.expandToProperty("_reorderLightsInScene")
  17661. ], Light.prototype, "renderPriority", void 0);
  17662. __decorate([
  17663. BABYLON.serialize()
  17664. ], Light.prototype, "shadowEnabled", void 0);
  17665. __decorate([
  17666. BABYLON.serialize("excludeWithLayerMask")
  17667. ], Light.prototype, "_excludeWithLayerMask", void 0);
  17668. __decorate([
  17669. BABYLON.serialize("includeOnlyWithLayerMask")
  17670. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  17671. __decorate([
  17672. BABYLON.serialize("lightmapMode")
  17673. ], Light.prototype, "_lightmapMode", void 0);
  17674. return Light;
  17675. }(BABYLON.Node));
  17676. BABYLON.Light = Light;
  17677. })(BABYLON || (BABYLON = {}));
  17678. //# sourceMappingURL=babylon.light.js.map
  17679. var BABYLON;
  17680. (function (BABYLON) {
  17681. var Camera = /** @class */ (function (_super) {
  17682. __extends(Camera, _super);
  17683. function Camera(name, position, scene) {
  17684. var _this = _super.call(this, name, scene) || this;
  17685. _this.upVector = BABYLON.Vector3.Up();
  17686. _this.orthoLeft = null;
  17687. _this.orthoRight = null;
  17688. _this.orthoBottom = null;
  17689. _this.orthoTop = null;
  17690. /**
  17691. * default : 0.8
  17692. * FOV is set in Radians.
  17693. */
  17694. _this.fov = 0.8;
  17695. _this.minZ = 1;
  17696. _this.maxZ = 10000.0;
  17697. _this.inertia = 0.9;
  17698. _this.mode = Camera.PERSPECTIVE_CAMERA;
  17699. _this.isIntermediate = false;
  17700. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  17701. /**
  17702. * Restricts the camera to viewing objects with the same layerMask.
  17703. * A camera with a layerMask of 1 will render meshes with no layerMask and meshes with a layerMask of 1.
  17704. */
  17705. _this.layerMask = 0x0FFFFFFF;
  17706. /**
  17707. * default : FOVMODE_VERTICAL_FIXED
  17708. * fovMode sets the camera frustum bounds to the viewport bounds.
  17709. */
  17710. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  17711. // Camera rig members
  17712. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  17713. _this._rigCameras = new Array();
  17714. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  17715. _this._skipRendering = false;
  17716. _this.customRenderTargets = new Array();
  17717. // Observables
  17718. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  17719. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  17720. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  17721. _this.onRestoreStateObservable = new BABYLON.Observable();
  17722. // Cache
  17723. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  17724. _this._projectionMatrix = new BABYLON.Matrix();
  17725. _this._doNotComputeProjectionMatrix = false;
  17726. _this._postProcesses = new Array();
  17727. _this._transformMatrix = BABYLON.Matrix.Zero();
  17728. _this._activeMeshes = new BABYLON.SmartArray(256);
  17729. _this._globalPosition = BABYLON.Vector3.Zero();
  17730. _this._refreshFrustumPlanes = true;
  17731. _this.getScene().addCamera(_this);
  17732. if (!_this.getScene().activeCamera) {
  17733. _this.getScene().activeCamera = _this;
  17734. }
  17735. _this.position = position;
  17736. return _this;
  17737. }
  17738. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  17739. get: function () {
  17740. return Camera._PERSPECTIVE_CAMERA;
  17741. },
  17742. enumerable: true,
  17743. configurable: true
  17744. });
  17745. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  17746. get: function () {
  17747. return Camera._ORTHOGRAPHIC_CAMERA;
  17748. },
  17749. enumerable: true,
  17750. configurable: true
  17751. });
  17752. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  17753. /**
  17754. * This is the default FOV mode for perspective cameras.
  17755. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  17756. *
  17757. */
  17758. get: function () {
  17759. return Camera._FOVMODE_VERTICAL_FIXED;
  17760. },
  17761. enumerable: true,
  17762. configurable: true
  17763. });
  17764. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  17765. /**
  17766. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  17767. *
  17768. */
  17769. get: function () {
  17770. return Camera._FOVMODE_HORIZONTAL_FIXED;
  17771. },
  17772. enumerable: true,
  17773. configurable: true
  17774. });
  17775. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  17776. get: function () {
  17777. return Camera._RIG_MODE_NONE;
  17778. },
  17779. enumerable: true,
  17780. configurable: true
  17781. });
  17782. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  17783. get: function () {
  17784. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  17785. },
  17786. enumerable: true,
  17787. configurable: true
  17788. });
  17789. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  17790. get: function () {
  17791. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  17792. },
  17793. enumerable: true,
  17794. configurable: true
  17795. });
  17796. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  17797. get: function () {
  17798. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17799. },
  17800. enumerable: true,
  17801. configurable: true
  17802. });
  17803. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  17804. get: function () {
  17805. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  17806. },
  17807. enumerable: true,
  17808. configurable: true
  17809. });
  17810. Object.defineProperty(Camera, "RIG_MODE_VR", {
  17811. get: function () {
  17812. return Camera._RIG_MODE_VR;
  17813. },
  17814. enumerable: true,
  17815. configurable: true
  17816. });
  17817. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  17818. get: function () {
  17819. return Camera._RIG_MODE_WEBVR;
  17820. },
  17821. enumerable: true,
  17822. configurable: true
  17823. });
  17824. /**
  17825. * Store current camera state (fov, position, etc..)
  17826. */
  17827. Camera.prototype.storeState = function () {
  17828. this._stateStored = true;
  17829. this._storedFov = this.fov;
  17830. return this;
  17831. };
  17832. /**
  17833. * Restores the camera state values if it has been stored. You must call storeState() first
  17834. */
  17835. Camera.prototype._restoreStateValues = function () {
  17836. if (!this._stateStored) {
  17837. return false;
  17838. }
  17839. this.fov = this._storedFov;
  17840. return true;
  17841. };
  17842. /**
  17843. * Restored camera state. You must call storeState() first
  17844. */
  17845. Camera.prototype.restoreState = function () {
  17846. if (this._restoreStateValues()) {
  17847. this.onRestoreStateObservable.notifyObservers(this);
  17848. return true;
  17849. }
  17850. return false;
  17851. };
  17852. Camera.prototype.getClassName = function () {
  17853. return "Camera";
  17854. };
  17855. /**
  17856. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17857. */
  17858. Camera.prototype.toString = function (fullDetails) {
  17859. var ret = "Name: " + this.name;
  17860. ret += ", type: " + this.getClassName();
  17861. if (this.animations) {
  17862. for (var i = 0; i < this.animations.length; i++) {
  17863. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17864. }
  17865. }
  17866. if (fullDetails) {
  17867. }
  17868. return ret;
  17869. };
  17870. Object.defineProperty(Camera.prototype, "globalPosition", {
  17871. get: function () {
  17872. return this._globalPosition;
  17873. },
  17874. enumerable: true,
  17875. configurable: true
  17876. });
  17877. Camera.prototype.getActiveMeshes = function () {
  17878. return this._activeMeshes;
  17879. };
  17880. Camera.prototype.isActiveMesh = function (mesh) {
  17881. return (this._activeMeshes.indexOf(mesh) !== -1);
  17882. };
  17883. //Cache
  17884. Camera.prototype._initCache = function () {
  17885. _super.prototype._initCache.call(this);
  17886. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17887. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17888. this._cache.mode = undefined;
  17889. this._cache.minZ = undefined;
  17890. this._cache.maxZ = undefined;
  17891. this._cache.fov = undefined;
  17892. this._cache.fovMode = undefined;
  17893. this._cache.aspectRatio = undefined;
  17894. this._cache.orthoLeft = undefined;
  17895. this._cache.orthoRight = undefined;
  17896. this._cache.orthoBottom = undefined;
  17897. this._cache.orthoTop = undefined;
  17898. this._cache.renderWidth = undefined;
  17899. this._cache.renderHeight = undefined;
  17900. };
  17901. Camera.prototype._updateCache = function (ignoreParentClass) {
  17902. if (!ignoreParentClass) {
  17903. _super.prototype._updateCache.call(this);
  17904. }
  17905. this._cache.position.copyFrom(this.position);
  17906. this._cache.upVector.copyFrom(this.upVector);
  17907. };
  17908. // Synchronized
  17909. Camera.prototype._isSynchronized = function () {
  17910. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  17911. };
  17912. Camera.prototype._isSynchronizedViewMatrix = function () {
  17913. if (!_super.prototype._isSynchronized.call(this))
  17914. return false;
  17915. return this._cache.position.equals(this.position)
  17916. && this._cache.upVector.equals(this.upVector)
  17917. && this.isSynchronizedWithParent();
  17918. };
  17919. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  17920. var check = this._cache.mode === this.mode
  17921. && this._cache.minZ === this.minZ
  17922. && this._cache.maxZ === this.maxZ;
  17923. if (!check) {
  17924. return false;
  17925. }
  17926. var engine = this.getEngine();
  17927. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  17928. check = this._cache.fov === this.fov
  17929. && this._cache.fovMode === this.fovMode
  17930. && this._cache.aspectRatio === engine.getAspectRatio(this);
  17931. }
  17932. else {
  17933. check = this._cache.orthoLeft === this.orthoLeft
  17934. && this._cache.orthoRight === this.orthoRight
  17935. && this._cache.orthoBottom === this.orthoBottom
  17936. && this._cache.orthoTop === this.orthoTop
  17937. && this._cache.renderWidth === engine.getRenderWidth()
  17938. && this._cache.renderHeight === engine.getRenderHeight();
  17939. }
  17940. return check;
  17941. };
  17942. // Controls
  17943. Camera.prototype.attachControl = function (element, noPreventDefault) {
  17944. };
  17945. Camera.prototype.detachControl = function (element) {
  17946. };
  17947. Camera.prototype.update = function () {
  17948. this._checkInputs();
  17949. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17950. this._updateRigCameras();
  17951. }
  17952. };
  17953. Camera.prototype._checkInputs = function () {
  17954. this.onAfterCheckInputsObservable.notifyObservers(this);
  17955. };
  17956. Object.defineProperty(Camera.prototype, "rigCameras", {
  17957. get: function () {
  17958. return this._rigCameras;
  17959. },
  17960. enumerable: true,
  17961. configurable: true
  17962. });
  17963. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  17964. get: function () {
  17965. return this._rigPostProcess;
  17966. },
  17967. enumerable: true,
  17968. configurable: true
  17969. });
  17970. Camera.prototype._cascadePostProcessesToRigCams = function () {
  17971. // invalidate framebuffer
  17972. if (this._postProcesses.length > 0) {
  17973. this._postProcesses[0].markTextureDirty();
  17974. }
  17975. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  17976. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  17977. var cam = this._rigCameras[i];
  17978. var rigPostProcess = cam._rigPostProcess;
  17979. // for VR rig, there does not have to be a post process
  17980. if (rigPostProcess) {
  17981. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  17982. if (isPass) {
  17983. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  17984. cam.isIntermediate = this._postProcesses.length === 0;
  17985. }
  17986. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  17987. rigPostProcess.markTextureDirty();
  17988. }
  17989. else {
  17990. cam._postProcesses = this._postProcesses.slice(0);
  17991. }
  17992. }
  17993. };
  17994. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  17995. if (insertAt === void 0) { insertAt = null; }
  17996. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  17997. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  17998. return 0;
  17999. }
  18000. if (insertAt == null || insertAt < 0) {
  18001. this._postProcesses.push(postProcess);
  18002. }
  18003. else {
  18004. this._postProcesses.splice(insertAt, 0, postProcess);
  18005. }
  18006. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18007. return this._postProcesses.indexOf(postProcess);
  18008. };
  18009. Camera.prototype.detachPostProcess = function (postProcess) {
  18010. var idx = this._postProcesses.indexOf(postProcess);
  18011. if (idx !== -1) {
  18012. this._postProcesses.splice(idx, 1);
  18013. }
  18014. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18015. };
  18016. Camera.prototype.getWorldMatrix = function () {
  18017. if (!this._worldMatrix) {
  18018. this._worldMatrix = BABYLON.Matrix.Identity();
  18019. }
  18020. var viewMatrix = this.getViewMatrix();
  18021. viewMatrix.invertToRef(this._worldMatrix);
  18022. return this._worldMatrix;
  18023. };
  18024. Camera.prototype._getViewMatrix = function () {
  18025. return BABYLON.Matrix.Identity();
  18026. };
  18027. Camera.prototype.getViewMatrix = function (force) {
  18028. if (!force && this._isSynchronizedViewMatrix()) {
  18029. return this._computedViewMatrix;
  18030. }
  18031. this.updateCache();
  18032. this._computedViewMatrix = this._getViewMatrix();
  18033. this._currentRenderId = this.getScene().getRenderId();
  18034. this._refreshFrustumPlanes = true;
  18035. if (!this.parent || !this.parent.getWorldMatrix) {
  18036. this._globalPosition.copyFrom(this.position);
  18037. }
  18038. else {
  18039. if (!this._worldMatrix) {
  18040. this._worldMatrix = BABYLON.Matrix.Identity();
  18041. }
  18042. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18043. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18044. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18045. this._computedViewMatrix.invert();
  18046. this._markSyncedWithParent();
  18047. }
  18048. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18049. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18050. }
  18051. this.onViewMatrixChangedObservable.notifyObservers(this);
  18052. return this._computedViewMatrix;
  18053. };
  18054. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18055. this._doNotComputeProjectionMatrix = true;
  18056. if (projection !== undefined) {
  18057. this._projectionMatrix = projection;
  18058. }
  18059. };
  18060. ;
  18061. Camera.prototype.unfreezeProjectionMatrix = function () {
  18062. this._doNotComputeProjectionMatrix = false;
  18063. };
  18064. ;
  18065. Camera.prototype.getProjectionMatrix = function (force) {
  18066. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18067. return this._projectionMatrix;
  18068. }
  18069. // Cache
  18070. this._cache.mode = this.mode;
  18071. this._cache.minZ = this.minZ;
  18072. this._cache.maxZ = this.maxZ;
  18073. // Matrix
  18074. this._refreshFrustumPlanes = true;
  18075. var engine = this.getEngine();
  18076. var scene = this.getScene();
  18077. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18078. this._cache.fov = this.fov;
  18079. this._cache.fovMode = this.fovMode;
  18080. this._cache.aspectRatio = engine.getAspectRatio(this);
  18081. if (this.minZ <= 0) {
  18082. this.minZ = 0.1;
  18083. }
  18084. if (scene.useRightHandedSystem) {
  18085. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18086. }
  18087. else {
  18088. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18089. }
  18090. }
  18091. else {
  18092. var halfWidth = engine.getRenderWidth() / 2.0;
  18093. var halfHeight = engine.getRenderHeight() / 2.0;
  18094. if (scene.useRightHandedSystem) {
  18095. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18096. }
  18097. else {
  18098. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18099. }
  18100. this._cache.orthoLeft = this.orthoLeft;
  18101. this._cache.orthoRight = this.orthoRight;
  18102. this._cache.orthoBottom = this.orthoBottom;
  18103. this._cache.orthoTop = this.orthoTop;
  18104. this._cache.renderWidth = engine.getRenderWidth();
  18105. this._cache.renderHeight = engine.getRenderHeight();
  18106. }
  18107. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18108. return this._projectionMatrix;
  18109. };
  18110. Camera.prototype.getTranformationMatrix = function () {
  18111. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18112. return this._transformMatrix;
  18113. };
  18114. Camera.prototype.updateFrustumPlanes = function () {
  18115. if (!this._refreshFrustumPlanes) {
  18116. return;
  18117. }
  18118. this.getTranformationMatrix();
  18119. if (!this._frustumPlanes) {
  18120. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18121. }
  18122. else {
  18123. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18124. }
  18125. this._refreshFrustumPlanes = false;
  18126. };
  18127. Camera.prototype.isInFrustum = function (target) {
  18128. this.updateFrustumPlanes();
  18129. return target.isInFrustum(this._frustumPlanes);
  18130. };
  18131. Camera.prototype.isCompletelyInFrustum = function (target) {
  18132. this.updateFrustumPlanes();
  18133. return target.isCompletelyInFrustum(this._frustumPlanes);
  18134. };
  18135. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18136. if (length === void 0) { length = 100; }
  18137. if (!transform) {
  18138. transform = this.getWorldMatrix();
  18139. }
  18140. if (!origin) {
  18141. origin = this.position;
  18142. }
  18143. var forward = new BABYLON.Vector3(0, 0, 1);
  18144. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18145. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18146. return new BABYLON.Ray(origin, direction, length);
  18147. };
  18148. Camera.prototype.dispose = function () {
  18149. // Observables
  18150. this.onViewMatrixChangedObservable.clear();
  18151. this.onProjectionMatrixChangedObservable.clear();
  18152. this.onAfterCheckInputsObservable.clear();
  18153. this.onRestoreStateObservable.clear();
  18154. // Inputs
  18155. if (this.inputs) {
  18156. this.inputs.clear();
  18157. }
  18158. // Animations
  18159. this.getScene().stopAnimation(this);
  18160. // Remove from scene
  18161. this.getScene().removeCamera(this);
  18162. while (this._rigCameras.length > 0) {
  18163. var camera = this._rigCameras.pop();
  18164. if (camera) {
  18165. camera.dispose();
  18166. }
  18167. }
  18168. // Postprocesses
  18169. if (this._rigPostProcess) {
  18170. this._rigPostProcess.dispose(this);
  18171. this._rigPostProcess = null;
  18172. this._postProcesses = [];
  18173. }
  18174. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18175. this._rigPostProcess = null;
  18176. this._postProcesses = [];
  18177. }
  18178. else {
  18179. var i = this._postProcesses.length;
  18180. while (--i >= 0) {
  18181. this._postProcesses[i].dispose(this);
  18182. }
  18183. }
  18184. // Render targets
  18185. var i = this.customRenderTargets.length;
  18186. while (--i >= 0) {
  18187. this.customRenderTargets[i].dispose();
  18188. }
  18189. this.customRenderTargets = [];
  18190. // Active Meshes
  18191. this._activeMeshes.dispose();
  18192. _super.prototype.dispose.call(this);
  18193. };
  18194. Object.defineProperty(Camera.prototype, "leftCamera", {
  18195. // ---- Camera rigs section ----
  18196. get: function () {
  18197. if (this._rigCameras.length < 1) {
  18198. return null;
  18199. }
  18200. return this._rigCameras[0];
  18201. },
  18202. enumerable: true,
  18203. configurable: true
  18204. });
  18205. Object.defineProperty(Camera.prototype, "rightCamera", {
  18206. get: function () {
  18207. if (this._rigCameras.length < 2) {
  18208. return null;
  18209. }
  18210. return this._rigCameras[1];
  18211. },
  18212. enumerable: true,
  18213. configurable: true
  18214. });
  18215. Camera.prototype.getLeftTarget = function () {
  18216. if (this._rigCameras.length < 1) {
  18217. return null;
  18218. }
  18219. return this._rigCameras[0].getTarget();
  18220. };
  18221. Camera.prototype.getRightTarget = function () {
  18222. if (this._rigCameras.length < 2) {
  18223. return null;
  18224. }
  18225. return this._rigCameras[1].getTarget();
  18226. };
  18227. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18228. if (this.cameraRigMode === mode) {
  18229. return;
  18230. }
  18231. while (this._rigCameras.length > 0) {
  18232. var camera = this._rigCameras.pop();
  18233. if (camera) {
  18234. camera.dispose();
  18235. }
  18236. }
  18237. this.cameraRigMode = mode;
  18238. this._cameraRigParams = {};
  18239. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18240. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18241. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18242. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18243. // create the rig cameras, unless none
  18244. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18245. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18246. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18247. if (leftCamera && rightCamera) {
  18248. this._rigCameras.push(leftCamera);
  18249. this._rigCameras.push(rightCamera);
  18250. }
  18251. }
  18252. switch (this.cameraRigMode) {
  18253. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18254. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18255. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18256. break;
  18257. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18258. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18259. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18260. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18261. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18262. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18263. break;
  18264. case Camera.RIG_MODE_VR:
  18265. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18266. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18267. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18268. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18269. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18270. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18271. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18272. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18273. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18274. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18275. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18276. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18277. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18278. if (metrics.compensateDistortion) {
  18279. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18280. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18281. }
  18282. break;
  18283. case Camera.RIG_MODE_WEBVR:
  18284. if (rigParams.vrDisplay) {
  18285. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18286. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18287. //Left eye
  18288. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18289. this._rigCameras[0].setCameraRigParameter("left", true);
  18290. //leaving this for future reference
  18291. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18292. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18293. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18294. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18295. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18296. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18297. this._rigCameras[0].parent = this;
  18298. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18299. //Right eye
  18300. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18301. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18302. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18303. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18304. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18305. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18306. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18307. this._rigCameras[1].parent = this;
  18308. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18309. if (Camera.UseAlternateWebVRRendering) {
  18310. this._rigCameras[1]._skipRendering = true;
  18311. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18312. }
  18313. }
  18314. break;
  18315. }
  18316. this._cascadePostProcessesToRigCams();
  18317. this.update();
  18318. };
  18319. Camera.prototype._getVRProjectionMatrix = function () {
  18320. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18321. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18322. return this._projectionMatrix;
  18323. };
  18324. Camera.prototype._updateCameraRotationMatrix = function () {
  18325. //Here for WebVR
  18326. };
  18327. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18328. //Here for WebVR
  18329. };
  18330. /**
  18331. * This function MUST be overwritten by the different WebVR cameras available.
  18332. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18333. */
  18334. Camera.prototype._getWebVRProjectionMatrix = function () {
  18335. return BABYLON.Matrix.Identity();
  18336. };
  18337. /**
  18338. * This function MUST be overwritten by the different WebVR cameras available.
  18339. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18340. */
  18341. Camera.prototype._getWebVRViewMatrix = function () {
  18342. return BABYLON.Matrix.Identity();
  18343. };
  18344. Camera.prototype.setCameraRigParameter = function (name, value) {
  18345. if (!this._cameraRigParams) {
  18346. this._cameraRigParams = {};
  18347. }
  18348. this._cameraRigParams[name] = value;
  18349. //provisionnally:
  18350. if (name === "interaxialDistance") {
  18351. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18352. }
  18353. };
  18354. /**
  18355. * needs to be overridden by children so sub has required properties to be copied
  18356. */
  18357. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18358. return null;
  18359. };
  18360. /**
  18361. * May need to be overridden by children
  18362. */
  18363. Camera.prototype._updateRigCameras = function () {
  18364. for (var i = 0; i < this._rigCameras.length; i++) {
  18365. this._rigCameras[i].minZ = this.minZ;
  18366. this._rigCameras[i].maxZ = this.maxZ;
  18367. this._rigCameras[i].fov = this.fov;
  18368. }
  18369. // only update viewport when ANAGLYPH
  18370. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18371. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18372. }
  18373. };
  18374. Camera.prototype._setupInputs = function () {
  18375. };
  18376. Camera.prototype.serialize = function () {
  18377. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18378. // Type
  18379. serializationObject.type = this.getClassName();
  18380. // Parent
  18381. if (this.parent) {
  18382. serializationObject.parentId = this.parent.id;
  18383. }
  18384. if (this.inputs) {
  18385. this.inputs.serialize(serializationObject);
  18386. }
  18387. // Animations
  18388. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18389. serializationObject.ranges = this.serializeAnimationRanges();
  18390. return serializationObject;
  18391. };
  18392. Camera.prototype.clone = function (name) {
  18393. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18394. };
  18395. Camera.prototype.getDirection = function (localAxis) {
  18396. var result = BABYLON.Vector3.Zero();
  18397. this.getDirectionToRef(localAxis, result);
  18398. return result;
  18399. };
  18400. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18401. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18402. };
  18403. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18404. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18405. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18406. switch (type) {
  18407. case "ArcRotateCamera":
  18408. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18409. case "DeviceOrientationCamera":
  18410. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18411. case "FollowCamera":
  18412. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18413. case "ArcFollowCamera":
  18414. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18415. case "GamepadCamera":
  18416. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18417. case "TouchCamera":
  18418. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18419. case "VirtualJoysticksCamera":
  18420. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18421. case "WebVRFreeCamera":
  18422. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18423. case "WebVRGamepadCamera":
  18424. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18425. case "VRDeviceOrientationFreeCamera":
  18426. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18427. case "VRDeviceOrientationGamepadCamera":
  18428. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18429. case "AnaglyphArcRotateCamera":
  18430. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18431. case "AnaglyphFreeCamera":
  18432. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18433. case "AnaglyphGamepadCamera":
  18434. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18435. case "AnaglyphUniversalCamera":
  18436. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18437. case "StereoscopicArcRotateCamera":
  18438. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18439. case "StereoscopicFreeCamera":
  18440. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18441. case "StereoscopicGamepadCamera":
  18442. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18443. case "StereoscopicUniversalCamera":
  18444. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18445. case "FreeCamera":// Forcing Universal here
  18446. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18447. default:// Universal Camera is the default value
  18448. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18449. }
  18450. };
  18451. Camera.prototype.computeWorldMatrix = function () {
  18452. return this.getWorldMatrix();
  18453. };
  18454. Camera.Parse = function (parsedCamera, scene) {
  18455. var type = parsedCamera.type;
  18456. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  18457. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  18458. // Parent
  18459. if (parsedCamera.parentId) {
  18460. camera._waitingParentId = parsedCamera.parentId;
  18461. }
  18462. //If camera has an input manager, let it parse inputs settings
  18463. if (camera.inputs) {
  18464. camera.inputs.parse(parsedCamera);
  18465. camera._setupInputs();
  18466. }
  18467. if (camera.setPosition) {
  18468. camera.position.copyFromFloats(0, 0, 0);
  18469. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  18470. }
  18471. // Target
  18472. if (parsedCamera.target) {
  18473. if (camera.setTarget) {
  18474. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18475. }
  18476. }
  18477. // Apply 3d rig, when found
  18478. if (parsedCamera.cameraRigMode) {
  18479. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  18480. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  18481. }
  18482. // Animations
  18483. if (parsedCamera.animations) {
  18484. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18485. var parsedAnimation = parsedCamera.animations[animationIndex];
  18486. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18487. }
  18488. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  18489. }
  18490. if (parsedCamera.autoAnimate) {
  18491. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  18492. }
  18493. return camera;
  18494. };
  18495. // Statics
  18496. Camera._PERSPECTIVE_CAMERA = 0;
  18497. Camera._ORTHOGRAPHIC_CAMERA = 1;
  18498. Camera._FOVMODE_VERTICAL_FIXED = 0;
  18499. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  18500. Camera._RIG_MODE_NONE = 0;
  18501. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  18502. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  18503. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  18504. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  18505. Camera._RIG_MODE_VR = 20;
  18506. Camera._RIG_MODE_WEBVR = 21;
  18507. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  18508. Camera.UseAlternateWebVRRendering = false;
  18509. __decorate([
  18510. BABYLON.serializeAsVector3()
  18511. ], Camera.prototype, "position", void 0);
  18512. __decorate([
  18513. BABYLON.serializeAsVector3()
  18514. ], Camera.prototype, "upVector", void 0);
  18515. __decorate([
  18516. BABYLON.serialize()
  18517. ], Camera.prototype, "orthoLeft", void 0);
  18518. __decorate([
  18519. BABYLON.serialize()
  18520. ], Camera.prototype, "orthoRight", void 0);
  18521. __decorate([
  18522. BABYLON.serialize()
  18523. ], Camera.prototype, "orthoBottom", void 0);
  18524. __decorate([
  18525. BABYLON.serialize()
  18526. ], Camera.prototype, "orthoTop", void 0);
  18527. __decorate([
  18528. BABYLON.serialize()
  18529. ], Camera.prototype, "fov", void 0);
  18530. __decorate([
  18531. BABYLON.serialize()
  18532. ], Camera.prototype, "minZ", void 0);
  18533. __decorate([
  18534. BABYLON.serialize()
  18535. ], Camera.prototype, "maxZ", void 0);
  18536. __decorate([
  18537. BABYLON.serialize()
  18538. ], Camera.prototype, "inertia", void 0);
  18539. __decorate([
  18540. BABYLON.serialize()
  18541. ], Camera.prototype, "mode", void 0);
  18542. __decorate([
  18543. BABYLON.serialize()
  18544. ], Camera.prototype, "layerMask", void 0);
  18545. __decorate([
  18546. BABYLON.serialize()
  18547. ], Camera.prototype, "fovMode", void 0);
  18548. __decorate([
  18549. BABYLON.serialize()
  18550. ], Camera.prototype, "cameraRigMode", void 0);
  18551. __decorate([
  18552. BABYLON.serialize()
  18553. ], Camera.prototype, "interaxialDistance", void 0);
  18554. __decorate([
  18555. BABYLON.serialize()
  18556. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  18557. return Camera;
  18558. }(BABYLON.Node));
  18559. BABYLON.Camera = Camera;
  18560. })(BABYLON || (BABYLON = {}));
  18561. //# sourceMappingURL=babylon.camera.js.map
  18562. var BABYLON;
  18563. (function (BABYLON) {
  18564. var RenderingManager = /** @class */ (function () {
  18565. function RenderingManager(scene) {
  18566. this._renderingGroups = new Array();
  18567. this._autoClearDepthStencil = {};
  18568. this._customOpaqueSortCompareFn = {};
  18569. this._customAlphaTestSortCompareFn = {};
  18570. this._customTransparentSortCompareFn = {};
  18571. this._renderinGroupInfo = null;
  18572. this._scene = scene;
  18573. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18574. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18575. }
  18576. }
  18577. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18578. if (depth === void 0) { depth = true; }
  18579. if (stencil === void 0) { stencil = true; }
  18580. if (this._depthStencilBufferAlreadyCleaned) {
  18581. return;
  18582. }
  18583. this._scene.getEngine().clear(null, false, depth, stencil);
  18584. this._depthStencilBufferAlreadyCleaned = true;
  18585. };
  18586. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18587. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18588. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18589. var info = null;
  18590. if (observable) {
  18591. if (!this._renderinGroupInfo) {
  18592. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18593. }
  18594. info = this._renderinGroupInfo;
  18595. info.scene = this._scene;
  18596. info.camera = this._scene.activeCamera;
  18597. }
  18598. // Dispatch sprites
  18599. if (renderSprites) {
  18600. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18601. var manager = this._scene.spriteManagers[index];
  18602. this.dispatchSprites(manager);
  18603. }
  18604. }
  18605. // Render
  18606. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18607. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18608. var renderingGroup = this._renderingGroups[index];
  18609. if (!renderingGroup && !observable)
  18610. continue;
  18611. var renderingGroupMask = 0;
  18612. // Fire PRECLEAR stage
  18613. if (observable && info) {
  18614. renderingGroupMask = Math.pow(2, index);
  18615. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18616. info.renderingGroupId = index;
  18617. observable.notifyObservers(info, renderingGroupMask);
  18618. }
  18619. // Clear depth/stencil if needed
  18620. if (RenderingManager.AUTOCLEAR) {
  18621. var autoClear = this._autoClearDepthStencil[index];
  18622. if (autoClear && autoClear.autoClear) {
  18623. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18624. }
  18625. }
  18626. if (observable && info) {
  18627. // Fire PREOPAQUE stage
  18628. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18629. observable.notifyObservers(info, renderingGroupMask);
  18630. // Fire PRETRANSPARENT stage
  18631. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18632. observable.notifyObservers(info, renderingGroupMask);
  18633. }
  18634. if (renderingGroup)
  18635. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18636. // Fire POSTTRANSPARENT stage
  18637. if (observable && info) {
  18638. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18639. observable.notifyObservers(info, renderingGroupMask);
  18640. }
  18641. }
  18642. };
  18643. RenderingManager.prototype.reset = function () {
  18644. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18645. var renderingGroup = this._renderingGroups[index];
  18646. if (renderingGroup) {
  18647. renderingGroup.prepare();
  18648. }
  18649. }
  18650. };
  18651. RenderingManager.prototype.dispose = function () {
  18652. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18653. var renderingGroup = this._renderingGroups[index];
  18654. if (renderingGroup) {
  18655. renderingGroup.dispose();
  18656. }
  18657. }
  18658. this._renderingGroups.length = 0;
  18659. };
  18660. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18661. if (this._renderingGroups[renderingGroupId] === undefined) {
  18662. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18663. }
  18664. };
  18665. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18666. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18667. this._prepareRenderingGroup(renderingGroupId);
  18668. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18669. };
  18670. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18671. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18672. this._prepareRenderingGroup(renderingGroupId);
  18673. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18674. };
  18675. /**
  18676. * @param subMesh The submesh to dispatch
  18677. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18678. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18679. */
  18680. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  18681. if (mesh === undefined) {
  18682. mesh = subMesh.getMesh();
  18683. }
  18684. var renderingGroupId = mesh.renderingGroupId || 0;
  18685. this._prepareRenderingGroup(renderingGroupId);
  18686. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  18687. };
  18688. /**
  18689. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18690. * This allowed control for front to back rendering or reversly depending of the special needs.
  18691. *
  18692. * @param renderingGroupId The rendering group id corresponding to its index
  18693. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18694. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18695. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18696. */
  18697. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18698. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18699. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18700. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18701. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18702. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18703. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18704. if (this._renderingGroups[renderingGroupId]) {
  18705. var group = this._renderingGroups[renderingGroupId];
  18706. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18707. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18708. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18709. }
  18710. };
  18711. /**
  18712. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18713. *
  18714. * @param renderingGroupId The rendering group id corresponding to its index
  18715. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18716. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18717. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18718. */
  18719. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18720. if (depth === void 0) { depth = true; }
  18721. if (stencil === void 0) { stencil = true; }
  18722. this._autoClearDepthStencil[renderingGroupId] = {
  18723. autoClear: autoClearDepthStencil,
  18724. depth: depth,
  18725. stencil: stencil
  18726. };
  18727. };
  18728. /**
  18729. * The max id used for rendering groups (not included)
  18730. */
  18731. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18732. /**
  18733. * The min id used for rendering groups (included)
  18734. */
  18735. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18736. /**
  18737. * Used to globally prevent autoclearing scenes.
  18738. */
  18739. RenderingManager.AUTOCLEAR = true;
  18740. return RenderingManager;
  18741. }());
  18742. BABYLON.RenderingManager = RenderingManager;
  18743. })(BABYLON || (BABYLON = {}));
  18744. //# sourceMappingURL=babylon.renderingManager.js.map
  18745. var BABYLON;
  18746. (function (BABYLON) {
  18747. var RenderingGroup = /** @class */ (function () {
  18748. /**
  18749. * Creates a new rendering group.
  18750. * @param index The rendering group index
  18751. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18752. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18753. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18754. */
  18755. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18756. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18757. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18758. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18759. this.index = index;
  18760. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18761. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18762. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18763. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  18764. this._particleSystems = new BABYLON.SmartArray(256);
  18765. this._spriteManagers = new BABYLON.SmartArray(256);
  18766. this._edgesRenderers = new BABYLON.SmartArray(16);
  18767. this._scene = scene;
  18768. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18769. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18770. this.transparentSortCompareFn = transparentSortCompareFn;
  18771. }
  18772. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18773. /**
  18774. * Set the opaque sort comparison function.
  18775. * If null the sub meshes will be render in the order they were created
  18776. */
  18777. set: function (value) {
  18778. this._opaqueSortCompareFn = value;
  18779. if (value) {
  18780. this._renderOpaque = this.renderOpaqueSorted;
  18781. }
  18782. else {
  18783. this._renderOpaque = RenderingGroup.renderUnsorted;
  18784. }
  18785. },
  18786. enumerable: true,
  18787. configurable: true
  18788. });
  18789. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18790. /**
  18791. * Set the alpha test sort comparison function.
  18792. * If null the sub meshes will be render in the order they were created
  18793. */
  18794. set: function (value) {
  18795. this._alphaTestSortCompareFn = value;
  18796. if (value) {
  18797. this._renderAlphaTest = this.renderAlphaTestSorted;
  18798. }
  18799. else {
  18800. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  18801. }
  18802. },
  18803. enumerable: true,
  18804. configurable: true
  18805. });
  18806. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  18807. /**
  18808. * Set the transparent sort comparison function.
  18809. * If null the sub meshes will be render in the order they were created
  18810. */
  18811. set: function (value) {
  18812. if (value) {
  18813. this._transparentSortCompareFn = value;
  18814. }
  18815. else {
  18816. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  18817. }
  18818. this._renderTransparent = this.renderTransparentSorted;
  18819. },
  18820. enumerable: true,
  18821. configurable: true
  18822. });
  18823. /**
  18824. * Render all the sub meshes contained in the group.
  18825. * @param customRenderFunction Used to override the default render behaviour of the group.
  18826. * @returns true if rendered some submeshes.
  18827. */
  18828. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  18829. if (customRenderFunction) {
  18830. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  18831. return;
  18832. }
  18833. var engine = this._scene.getEngine();
  18834. // Depth only
  18835. if (this._depthOnlySubMeshes.length !== 0) {
  18836. engine.setColorWrite(false);
  18837. this._renderAlphaTest(this._depthOnlySubMeshes);
  18838. engine.setColorWrite(true);
  18839. }
  18840. // Opaque
  18841. if (this._opaqueSubMeshes.length !== 0) {
  18842. this._renderOpaque(this._opaqueSubMeshes);
  18843. }
  18844. // Alpha test
  18845. if (this._alphaTestSubMeshes.length !== 0) {
  18846. this._renderAlphaTest(this._alphaTestSubMeshes);
  18847. }
  18848. var stencilState = engine.getStencilBuffer();
  18849. engine.setStencilBuffer(false);
  18850. // Sprites
  18851. if (renderSprites) {
  18852. this._renderSprites();
  18853. }
  18854. // Particles
  18855. if (renderParticles) {
  18856. this._renderParticles(activeMeshes);
  18857. }
  18858. if (this.onBeforeTransparentRendering) {
  18859. this.onBeforeTransparentRendering();
  18860. }
  18861. // Transparent
  18862. if (this._transparentSubMeshes.length !== 0) {
  18863. this._renderTransparent(this._transparentSubMeshes);
  18864. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18865. }
  18866. // Set back stencil to false in case it changes before the edge renderer.
  18867. engine.setStencilBuffer(false);
  18868. // Edges
  18869. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18870. this._edgesRenderers.data[edgesRendererIndex].render();
  18871. }
  18872. // Restore Stencil state.
  18873. engine.setStencilBuffer(stencilState);
  18874. };
  18875. /**
  18876. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  18877. * @param subMeshes The submeshes to render
  18878. */
  18879. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  18880. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  18881. };
  18882. /**
  18883. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  18884. * @param subMeshes The submeshes to render
  18885. */
  18886. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  18887. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  18888. };
  18889. /**
  18890. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  18891. * @param subMeshes The submeshes to render
  18892. */
  18893. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18894. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  18895. };
  18896. /**
  18897. * Renders the submeshes in a specified order.
  18898. * @param subMeshes The submeshes to sort before render
  18899. * @param sortCompareFn The comparison function use to sort
  18900. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18901. * @param transparent Specifies to activate blending if true
  18902. */
  18903. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  18904. var subIndex = 0;
  18905. var subMesh;
  18906. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  18907. for (; subIndex < subMeshes.length; subIndex++) {
  18908. subMesh = subMeshes.data[subIndex];
  18909. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18910. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18911. }
  18912. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18913. if (sortCompareFn) {
  18914. sortedArray.sort(sortCompareFn);
  18915. }
  18916. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18917. subMesh = sortedArray[subIndex];
  18918. if (transparent) {
  18919. var material = subMesh.getMaterial();
  18920. if (material && material.needDepthPrePass) {
  18921. var engine = material.getScene().getEngine();
  18922. engine.setColorWrite(false);
  18923. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18924. subMesh.render(false);
  18925. engine.setColorWrite(true);
  18926. }
  18927. }
  18928. subMesh.render(transparent);
  18929. }
  18930. };
  18931. /**
  18932. * Renders the submeshes in the order they were dispatched (no sort applied).
  18933. * @param subMeshes The submeshes to render
  18934. */
  18935. RenderingGroup.renderUnsorted = function (subMeshes) {
  18936. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18937. var submesh = subMeshes.data[subIndex];
  18938. submesh.render(false);
  18939. }
  18940. };
  18941. /**
  18942. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18943. * are rendered back to front if in the same alpha index.
  18944. *
  18945. * @param a The first submesh
  18946. * @param b The second submesh
  18947. * @returns The result of the comparison
  18948. */
  18949. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  18950. // Alpha index first
  18951. if (a._alphaIndex > b._alphaIndex) {
  18952. return 1;
  18953. }
  18954. if (a._alphaIndex < b._alphaIndex) {
  18955. return -1;
  18956. }
  18957. // Then distance to camera
  18958. return RenderingGroup.backToFrontSortCompare(a, b);
  18959. };
  18960. /**
  18961. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18962. * are rendered back to front.
  18963. *
  18964. * @param a The first submesh
  18965. * @param b The second submesh
  18966. * @returns The result of the comparison
  18967. */
  18968. RenderingGroup.backToFrontSortCompare = function (a, b) {
  18969. // Then distance to camera
  18970. if (a._distanceToCamera < b._distanceToCamera) {
  18971. return 1;
  18972. }
  18973. if (a._distanceToCamera > b._distanceToCamera) {
  18974. return -1;
  18975. }
  18976. return 0;
  18977. };
  18978. /**
  18979. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18980. * are rendered front to back (prevent overdraw).
  18981. *
  18982. * @param a The first submesh
  18983. * @param b The second submesh
  18984. * @returns The result of the comparison
  18985. */
  18986. RenderingGroup.frontToBackSortCompare = function (a, b) {
  18987. // Then distance to camera
  18988. if (a._distanceToCamera < b._distanceToCamera) {
  18989. return -1;
  18990. }
  18991. if (a._distanceToCamera > b._distanceToCamera) {
  18992. return 1;
  18993. }
  18994. return 0;
  18995. };
  18996. /**
  18997. * Resets the different lists of submeshes to prepare a new frame.
  18998. */
  18999. RenderingGroup.prototype.prepare = function () {
  19000. this._opaqueSubMeshes.reset();
  19001. this._transparentSubMeshes.reset();
  19002. this._alphaTestSubMeshes.reset();
  19003. this._depthOnlySubMeshes.reset();
  19004. this._particleSystems.reset();
  19005. this._spriteManagers.reset();
  19006. this._edgesRenderers.reset();
  19007. };
  19008. RenderingGroup.prototype.dispose = function () {
  19009. this._opaqueSubMeshes.dispose();
  19010. this._transparentSubMeshes.dispose();
  19011. this._alphaTestSubMeshes.dispose();
  19012. this._depthOnlySubMeshes.dispose();
  19013. this._particleSystems.dispose();
  19014. this._spriteManagers.dispose();
  19015. this._edgesRenderers.dispose();
  19016. };
  19017. /**
  19018. * Inserts the submesh in its correct queue depending on its material.
  19019. * @param subMesh The submesh to dispatch
  19020. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19021. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19022. */
  19023. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19024. // Get mesh and materials if not provided
  19025. if (mesh === undefined) {
  19026. mesh = subMesh.getMesh();
  19027. }
  19028. if (material === undefined) {
  19029. material = subMesh.getMaterial();
  19030. }
  19031. if (material === null || material === undefined) {
  19032. return;
  19033. }
  19034. if (material.needAlphaBlendingForMesh(mesh)) {
  19035. this._transparentSubMeshes.push(subMesh);
  19036. }
  19037. else if (material.needAlphaTesting()) {
  19038. if (material.needDepthPrePass) {
  19039. this._depthOnlySubMeshes.push(subMesh);
  19040. }
  19041. this._alphaTestSubMeshes.push(subMesh);
  19042. }
  19043. else {
  19044. if (material.needDepthPrePass) {
  19045. this._depthOnlySubMeshes.push(subMesh);
  19046. }
  19047. this._opaqueSubMeshes.push(subMesh); // Opaque
  19048. }
  19049. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19050. this._edgesRenderers.push(mesh._edgesRenderer);
  19051. }
  19052. };
  19053. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19054. this._spriteManagers.push(spriteManager);
  19055. };
  19056. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19057. this._particleSystems.push(particleSystem);
  19058. };
  19059. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19060. if (this._particleSystems.length === 0) {
  19061. return;
  19062. }
  19063. // Particles
  19064. var activeCamera = this._scene.activeCamera;
  19065. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19066. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19067. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19068. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19069. continue;
  19070. }
  19071. var emitter = particleSystem.emitter;
  19072. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19073. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19074. }
  19075. }
  19076. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19077. };
  19078. RenderingGroup.prototype._renderSprites = function () {
  19079. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19080. return;
  19081. }
  19082. // Sprites
  19083. var activeCamera = this._scene.activeCamera;
  19084. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19085. for (var id = 0; id < this._spriteManagers.length; id++) {
  19086. var spriteManager = this._spriteManagers.data[id];
  19087. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19088. spriteManager.render();
  19089. }
  19090. }
  19091. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19092. };
  19093. return RenderingGroup;
  19094. }());
  19095. BABYLON.RenderingGroup = RenderingGroup;
  19096. })(BABYLON || (BABYLON = {}));
  19097. //# sourceMappingURL=babylon.renderingGroup.js.map
  19098. var BABYLON;
  19099. (function (BABYLON) {
  19100. var ClickInfo = /** @class */ (function () {
  19101. function ClickInfo() {
  19102. this._singleClick = false;
  19103. this._doubleClick = false;
  19104. this._hasSwiped = false;
  19105. this._ignore = false;
  19106. }
  19107. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19108. get: function () {
  19109. return this._singleClick;
  19110. },
  19111. set: function (b) {
  19112. this._singleClick = b;
  19113. },
  19114. enumerable: true,
  19115. configurable: true
  19116. });
  19117. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19118. get: function () {
  19119. return this._doubleClick;
  19120. },
  19121. set: function (b) {
  19122. this._doubleClick = b;
  19123. },
  19124. enumerable: true,
  19125. configurable: true
  19126. });
  19127. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19128. get: function () {
  19129. return this._hasSwiped;
  19130. },
  19131. set: function (b) {
  19132. this._hasSwiped = b;
  19133. },
  19134. enumerable: true,
  19135. configurable: true
  19136. });
  19137. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19138. get: function () {
  19139. return this._ignore;
  19140. },
  19141. set: function (b) {
  19142. this._ignore = b;
  19143. },
  19144. enumerable: true,
  19145. configurable: true
  19146. });
  19147. return ClickInfo;
  19148. }());
  19149. /**
  19150. * This class is used by the onRenderingGroupObservable
  19151. */
  19152. var RenderingGroupInfo = /** @class */ (function () {
  19153. function RenderingGroupInfo() {
  19154. }
  19155. /**
  19156. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19157. * This stage will be fired no matter what
  19158. */
  19159. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19160. /**
  19161. * Called before opaque object are rendered.
  19162. * This stage will be fired only if there's 3D Opaque content to render
  19163. */
  19164. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19165. /**
  19166. * Called after the opaque objects are rendered and before the transparent ones
  19167. * This stage will be fired only if there's 3D transparent content to render
  19168. */
  19169. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19170. /**
  19171. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19172. * This stage will be fired no matter what
  19173. */
  19174. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19175. return RenderingGroupInfo;
  19176. }());
  19177. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19178. /**
  19179. * Represents a scene to be rendered by the engine.
  19180. * @see http://doc.babylonjs.com/page.php?p=21911
  19181. */
  19182. var Scene = /** @class */ (function () {
  19183. /**
  19184. * @constructor
  19185. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19186. */
  19187. function Scene(engine) {
  19188. // Members
  19189. this.autoClear = true;
  19190. this.autoClearDepthAndStencil = true;
  19191. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19192. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19193. this.forceWireframe = false;
  19194. this._forcePointsCloud = false;
  19195. this.forceShowBoundingBoxes = false;
  19196. this.animationsEnabled = true;
  19197. this.useConstantAnimationDeltaTime = false;
  19198. this.constantlyUpdateMeshUnderPointer = false;
  19199. this.hoverCursor = "pointer";
  19200. this.defaultCursor = "";
  19201. /**
  19202. * This is used to call preventDefault() on pointer down
  19203. * in order to block unwanted artifacts like system double clicks
  19204. */
  19205. this.preventDefaultOnPointerDown = true;
  19206. // Metadata
  19207. this.metadata = null;
  19208. /**
  19209. * An event triggered when the scene is disposed.
  19210. * @type {BABYLON.Observable}
  19211. */
  19212. this.onDisposeObservable = new BABYLON.Observable();
  19213. /**
  19214. * An event triggered before rendering the scene (right after animations and physics)
  19215. * @type {BABYLON.Observable}
  19216. */
  19217. this.onBeforeRenderObservable = new BABYLON.Observable();
  19218. /**
  19219. * An event triggered after rendering the scene
  19220. * @type {BABYLON.Observable}
  19221. */
  19222. this.onAfterRenderObservable = new BABYLON.Observable();
  19223. /**
  19224. * An event triggered before animating the scene
  19225. * @type {BABYLON.Observable}
  19226. */
  19227. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19228. /**
  19229. * An event triggered after animations processing
  19230. * @type {BABYLON.Observable}
  19231. */
  19232. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19233. /**
  19234. * An event triggered before draw calls are ready to be sent
  19235. * @type {BABYLON.Observable}
  19236. */
  19237. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19238. /**
  19239. * An event triggered after draw calls have been sent
  19240. * @type {BABYLON.Observable}
  19241. */
  19242. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19243. /**
  19244. * An event triggered when physic simulation is about to be run
  19245. * @type {BABYLON.Observable}
  19246. */
  19247. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19248. /**
  19249. * An event triggered when physic simulation has been done
  19250. * @type {BABYLON.Observable}
  19251. */
  19252. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19253. /**
  19254. * An event triggered when the scene is ready
  19255. * @type {BABYLON.Observable}
  19256. */
  19257. this.onReadyObservable = new BABYLON.Observable();
  19258. /**
  19259. * An event triggered before rendering a camera
  19260. * @type {BABYLON.Observable}
  19261. */
  19262. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19263. /**
  19264. * An event triggered after rendering a camera
  19265. * @type {BABYLON.Observable}
  19266. */
  19267. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19268. /**
  19269. * An event triggered when active meshes evaluation is about to start
  19270. * @type {BABYLON.Observable}
  19271. */
  19272. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19273. /**
  19274. * An event triggered when active meshes evaluation is done
  19275. * @type {BABYLON.Observable}
  19276. */
  19277. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19278. /**
  19279. * An event triggered when particles rendering is about to start
  19280. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19281. * @type {BABYLON.Observable}
  19282. */
  19283. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19284. /**
  19285. * An event triggered when particles rendering is done
  19286. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19287. * @type {BABYLON.Observable}
  19288. */
  19289. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19290. /**
  19291. * An event triggered when sprites rendering is about to start
  19292. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19293. * @type {BABYLON.Observable}
  19294. */
  19295. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19296. /**
  19297. * An event triggered when sprites rendering is done
  19298. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19299. * @type {BABYLON.Observable}
  19300. */
  19301. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19302. /**
  19303. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19304. * @type {BABYLON.Observable}
  19305. */
  19306. this.onDataLoadedObservable = new BABYLON.Observable();
  19307. /**
  19308. * An event triggered when a camera is created
  19309. * @type {BABYLON.Observable}
  19310. */
  19311. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19312. /**
  19313. * An event triggered when a camera is removed
  19314. * @type {BABYLON.Observable}
  19315. */
  19316. this.onCameraRemovedObservable = new BABYLON.Observable();
  19317. /**
  19318. * An event triggered when a light is created
  19319. * @type {BABYLON.Observable}
  19320. */
  19321. this.onNewLightAddedObservable = new BABYLON.Observable();
  19322. /**
  19323. * An event triggered when a light is removed
  19324. * @type {BABYLON.Observable}
  19325. */
  19326. this.onLightRemovedObservable = new BABYLON.Observable();
  19327. /**
  19328. * An event triggered when a geometry is created
  19329. * @type {BABYLON.Observable}
  19330. */
  19331. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19332. /**
  19333. * An event triggered when a geometry is removed
  19334. * @type {BABYLON.Observable}
  19335. */
  19336. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19337. /**
  19338. * An event triggered when a transform node is created
  19339. * @type {BABYLON.Observable}
  19340. */
  19341. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19342. /**
  19343. * An event triggered when a transform node is removed
  19344. * @type {BABYLON.Observable}
  19345. */
  19346. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19347. /**
  19348. * An event triggered when a mesh is created
  19349. * @type {BABYLON.Observable}
  19350. */
  19351. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19352. /**
  19353. * An event triggered when a mesh is removed
  19354. * @type {BABYLON.Observable}
  19355. */
  19356. this.onMeshRemovedObservable = new BABYLON.Observable();
  19357. /**
  19358. * An event triggered when render targets are about to be rendered
  19359. * Can happen multiple times per frame.
  19360. * @type {BABYLON.Observable}
  19361. */
  19362. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19363. /**
  19364. * An event triggered when render targets were rendered.
  19365. * Can happen multiple times per frame.
  19366. * @type {BABYLON.Observable}
  19367. */
  19368. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19369. /**
  19370. * An event triggered before calculating deterministic simulation step
  19371. * @type {BABYLON.Observable}
  19372. */
  19373. this.onBeforeStepObservable = new BABYLON.Observable();
  19374. /**
  19375. * An event triggered after calculating deterministic simulation step
  19376. * @type {BABYLON.Observable}
  19377. */
  19378. this.onAfterStepObservable = new BABYLON.Observable();
  19379. /**
  19380. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19381. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19382. * 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)
  19383. */
  19384. this.onRenderingGroupObservable = new BABYLON.Observable();
  19385. // Animations
  19386. this.animations = [];
  19387. /**
  19388. * 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).
  19389. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19390. */
  19391. this.onPrePointerObservable = new BABYLON.Observable();
  19392. /**
  19393. * Observable event triggered each time an input event is received from the rendering canvas
  19394. */
  19395. this.onPointerObservable = new BABYLON.Observable();
  19396. this._meshPickProceed = false;
  19397. this._currentPickResult = null;
  19398. this._previousPickResult = null;
  19399. this._totalPointersPressed = 0;
  19400. this._doubleClickOccured = false;
  19401. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19402. this.cameraToUseForPointers = null;
  19403. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19404. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19405. this._startingPointerTime = 0;
  19406. this._previousStartingPointerTime = 0;
  19407. // Deterministic lockstep
  19408. this._timeAccumulator = 0;
  19409. this._currentStepId = 0;
  19410. this._currentInternalStep = 0;
  19411. // Keyboard
  19412. /**
  19413. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19414. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19415. */
  19416. this.onPreKeyboardObservable = new BABYLON.Observable();
  19417. /**
  19418. * Observable event triggered each time an keyboard event is received from the hosting window
  19419. */
  19420. this.onKeyboardObservable = new BABYLON.Observable();
  19421. // Coordinate system
  19422. /**
  19423. * use right-handed coordinate system on this scene.
  19424. * @type {boolean}
  19425. */
  19426. this._useRightHandedSystem = false;
  19427. // Fog
  19428. this._fogEnabled = true;
  19429. this._fogMode = Scene.FOGMODE_NONE;
  19430. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19431. this.fogDensity = 0.1;
  19432. this.fogStart = 0;
  19433. this.fogEnd = 1000.0;
  19434. // Lights
  19435. /**
  19436. * is shadow enabled on this scene.
  19437. * @type {boolean}
  19438. */
  19439. this._shadowsEnabled = true;
  19440. /**
  19441. * is light enabled on this scene.
  19442. * @type {boolean}
  19443. */
  19444. this._lightsEnabled = true;
  19445. /**
  19446. * All of the lights added to this scene.
  19447. * @see BABYLON.Light
  19448. * @type {BABYLON.Light[]}
  19449. */
  19450. this.lights = new Array();
  19451. // Cameras
  19452. /** All of the cameras added to this scene. */
  19453. this.cameras = new Array();
  19454. /** All of the active cameras added to this scene. */
  19455. this.activeCameras = new Array();
  19456. // Meshes
  19457. /**
  19458. * All of the tranform nodes added to this scene.
  19459. * @see BABYLON.TransformNode
  19460. * @type {BABYLON.TransformNode[]}
  19461. */
  19462. this.transformNodes = new Array();
  19463. /**
  19464. * All of the (abstract) meshes added to this scene.
  19465. * @see BABYLON.AbstractMesh
  19466. * @type {BABYLON.AbstractMesh[]}
  19467. */
  19468. this.meshes = new Array();
  19469. /**
  19470. * All of the animation groups added to this scene.
  19471. * @see BABYLON.AnimationGroup
  19472. * @type {BABYLON.AnimationGroup[]}
  19473. */
  19474. this.animationGroups = new Array();
  19475. // Geometries
  19476. this._geometries = new Array();
  19477. this.materials = new Array();
  19478. this.multiMaterials = new Array();
  19479. // Textures
  19480. this._texturesEnabled = true;
  19481. this.textures = new Array();
  19482. // Particles
  19483. this.particlesEnabled = true;
  19484. this.particleSystems = new Array();
  19485. // Sprites
  19486. this.spritesEnabled = true;
  19487. this.spriteManagers = new Array();
  19488. // Layers
  19489. this.layers = new Array();
  19490. this.highlightLayers = new Array();
  19491. // Skeletons
  19492. this._skeletonsEnabled = true;
  19493. this.skeletons = new Array();
  19494. // Morph targets
  19495. this.morphTargetManagers = new Array();
  19496. // Lens flares
  19497. this.lensFlaresEnabled = true;
  19498. this.lensFlareSystems = new Array();
  19499. // Collisions
  19500. this.collisionsEnabled = true;
  19501. /** Defines the gravity applied to this scene */
  19502. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19503. // Postprocesses
  19504. this.postProcesses = new Array();
  19505. this.postProcessesEnabled = true;
  19506. // Customs render targets
  19507. this.renderTargetsEnabled = true;
  19508. this.dumpNextRenderTargets = false;
  19509. this.customRenderTargets = new Array();
  19510. // Imported meshes
  19511. this.importedMeshesFiles = new Array();
  19512. // Probes
  19513. this.probesEnabled = true;
  19514. this.reflectionProbes = new Array();
  19515. this._actionManagers = new Array();
  19516. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  19517. // Procedural textures
  19518. this.proceduralTexturesEnabled = true;
  19519. this._proceduralTextures = new Array();
  19520. this.soundTracks = new Array();
  19521. this._audioEnabled = true;
  19522. this._headphone = false;
  19523. // Performance counters
  19524. this._totalVertices = new BABYLON.PerfCounter();
  19525. this._activeIndices = new BABYLON.PerfCounter();
  19526. this._activeParticles = new BABYLON.PerfCounter();
  19527. this._activeBones = new BABYLON.PerfCounter();
  19528. this._animationTime = 0;
  19529. this.animationTimeScale = 1;
  19530. this._renderId = 0;
  19531. this._executeWhenReadyTimeoutId = -1;
  19532. this._intermediateRendering = false;
  19533. this._viewUpdateFlag = -1;
  19534. this._projectionUpdateFlag = -1;
  19535. this._alternateViewUpdateFlag = -1;
  19536. this._alternateProjectionUpdateFlag = -1;
  19537. this._toBeDisposed = new BABYLON.SmartArray(256);
  19538. this._activeRequests = new Array();
  19539. this._pendingData = new Array();
  19540. this._isDisposed = false;
  19541. this.dispatchAllSubMeshesOfActiveMeshes = false;
  19542. this._activeMeshes = new BABYLON.SmartArray(256);
  19543. this._processedMaterials = new BABYLON.SmartArray(256);
  19544. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  19545. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19546. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  19547. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  19548. this._activeAnimatables = new Array();
  19549. this._transformMatrix = BABYLON.Matrix.Zero();
  19550. this._useAlternateCameraConfiguration = false;
  19551. this._alternateRendering = false;
  19552. this.requireLightSorting = false;
  19553. this._activeMeshesFrozen = false;
  19554. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  19555. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19556. this._engine.scenes.push(this);
  19557. this._uid = null;
  19558. this._renderingManager = new BABYLON.RenderingManager(this);
  19559. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19560. if (BABYLON.OutlineRenderer) {
  19561. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19562. }
  19563. if (BABYLON.Tools.IsWindowObjectExist()) {
  19564. this.attachControl();
  19565. }
  19566. //simplification queue
  19567. if (BABYLON.SimplificationQueue) {
  19568. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19569. }
  19570. //collision coordinator initialization. For now legacy per default.
  19571. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19572. // Uniform Buffer
  19573. this._createUbo();
  19574. // Default Image processing definition.
  19575. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  19576. }
  19577. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19578. /** The fog is deactivated */
  19579. get: function () {
  19580. return Scene._FOGMODE_NONE;
  19581. },
  19582. enumerable: true,
  19583. configurable: true
  19584. });
  19585. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19586. /** The fog density is following an exponential function */
  19587. get: function () {
  19588. return Scene._FOGMODE_EXP;
  19589. },
  19590. enumerable: true,
  19591. configurable: true
  19592. });
  19593. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19594. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  19595. get: function () {
  19596. return Scene._FOGMODE_EXP2;
  19597. },
  19598. enumerable: true,
  19599. configurable: true
  19600. });
  19601. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19602. /** The fog density is following a linear function. */
  19603. get: function () {
  19604. return Scene._FOGMODE_LINEAR;
  19605. },
  19606. enumerable: true,
  19607. configurable: true
  19608. });
  19609. Object.defineProperty(Scene.prototype, "environmentTexture", {
  19610. /**
  19611. * Texture used in all pbr material as the reflection texture.
  19612. * As in the majority of the scene they are the same (exception for multi room and so on),
  19613. * this is easier to reference from here than from all the materials.
  19614. */
  19615. get: function () {
  19616. return this._environmentTexture;
  19617. },
  19618. /**
  19619. * Texture used in all pbr material as the reflection texture.
  19620. * As in the majority of the scene they are the same (exception for multi room and so on),
  19621. * this is easier to set here than in all the materials.
  19622. */
  19623. set: function (value) {
  19624. if (this._environmentTexture === value) {
  19625. return;
  19626. }
  19627. this._environmentTexture = value;
  19628. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19629. },
  19630. enumerable: true,
  19631. configurable: true
  19632. });
  19633. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  19634. /**
  19635. * Default image processing configuration used either in the rendering
  19636. * Forward main pass or through the imageProcessingPostProcess if present.
  19637. * As in the majority of the scene they are the same (exception for multi camera),
  19638. * this is easier to reference from here than from all the materials and post process.
  19639. *
  19640. * No setter as we it is a shared configuration, you can set the values instead.
  19641. */
  19642. get: function () {
  19643. return this._imageProcessingConfiguration;
  19644. },
  19645. enumerable: true,
  19646. configurable: true
  19647. });
  19648. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  19649. get: function () {
  19650. return this._forcePointsCloud;
  19651. },
  19652. set: function (value) {
  19653. if (this._forcePointsCloud === value) {
  19654. return;
  19655. }
  19656. this._forcePointsCloud = value;
  19657. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19658. },
  19659. enumerable: true,
  19660. configurable: true
  19661. });
  19662. Object.defineProperty(Scene.prototype, "onDispose", {
  19663. /** A function to be executed when this scene is disposed. */
  19664. set: function (callback) {
  19665. if (this._onDisposeObserver) {
  19666. this.onDisposeObservable.remove(this._onDisposeObserver);
  19667. }
  19668. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19669. },
  19670. enumerable: true,
  19671. configurable: true
  19672. });
  19673. Object.defineProperty(Scene.prototype, "beforeRender", {
  19674. /** A function to be executed before rendering this scene */
  19675. set: function (callback) {
  19676. if (this._onBeforeRenderObserver) {
  19677. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19678. }
  19679. if (callback) {
  19680. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19681. }
  19682. },
  19683. enumerable: true,
  19684. configurable: true
  19685. });
  19686. Object.defineProperty(Scene.prototype, "afterRender", {
  19687. /** A function to be executed after rendering this scene */
  19688. set: function (callback) {
  19689. if (this._onAfterRenderObserver) {
  19690. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19691. }
  19692. if (callback) {
  19693. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19694. }
  19695. },
  19696. enumerable: true,
  19697. configurable: true
  19698. });
  19699. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19700. set: function (callback) {
  19701. if (this._onBeforeCameraRenderObserver) {
  19702. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19703. }
  19704. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19705. },
  19706. enumerable: true,
  19707. configurable: true
  19708. });
  19709. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19710. set: function (callback) {
  19711. if (this._onAfterCameraRenderObserver) {
  19712. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19713. }
  19714. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19715. },
  19716. enumerable: true,
  19717. configurable: true
  19718. });
  19719. Object.defineProperty(Scene.prototype, "gamepadManager", {
  19720. get: function () {
  19721. if (!this._gamepadManager) {
  19722. this._gamepadManager = new BABYLON.GamepadManager(this);
  19723. }
  19724. return this._gamepadManager;
  19725. },
  19726. enumerable: true,
  19727. configurable: true
  19728. });
  19729. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19730. get: function () {
  19731. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19732. },
  19733. enumerable: true,
  19734. configurable: true
  19735. });
  19736. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  19737. get: function () {
  19738. return this._useRightHandedSystem;
  19739. },
  19740. set: function (value) {
  19741. if (this._useRightHandedSystem === value) {
  19742. return;
  19743. }
  19744. this._useRightHandedSystem = value;
  19745. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19746. },
  19747. enumerable: true,
  19748. configurable: true
  19749. });
  19750. Scene.prototype.setStepId = function (newStepId) {
  19751. this._currentStepId = newStepId;
  19752. };
  19753. ;
  19754. Scene.prototype.getStepId = function () {
  19755. return this._currentStepId;
  19756. };
  19757. ;
  19758. Scene.prototype.getInternalStep = function () {
  19759. return this._currentInternalStep;
  19760. };
  19761. ;
  19762. Object.defineProperty(Scene.prototype, "fogEnabled", {
  19763. get: function () {
  19764. return this._fogEnabled;
  19765. },
  19766. /**
  19767. * is fog enabled on this scene.
  19768. */
  19769. set: function (value) {
  19770. if (this._fogEnabled === value) {
  19771. return;
  19772. }
  19773. this._fogEnabled = value;
  19774. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19775. },
  19776. enumerable: true,
  19777. configurable: true
  19778. });
  19779. Object.defineProperty(Scene.prototype, "fogMode", {
  19780. get: function () {
  19781. return this._fogMode;
  19782. },
  19783. set: function (value) {
  19784. if (this._fogMode === value) {
  19785. return;
  19786. }
  19787. this._fogMode = value;
  19788. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19789. },
  19790. enumerable: true,
  19791. configurable: true
  19792. });
  19793. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  19794. get: function () {
  19795. return this._shadowsEnabled;
  19796. },
  19797. set: function (value) {
  19798. if (this._shadowsEnabled === value) {
  19799. return;
  19800. }
  19801. this._shadowsEnabled = value;
  19802. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19803. },
  19804. enumerable: true,
  19805. configurable: true
  19806. });
  19807. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  19808. get: function () {
  19809. return this._lightsEnabled;
  19810. },
  19811. set: function (value) {
  19812. if (this._lightsEnabled === value) {
  19813. return;
  19814. }
  19815. this._lightsEnabled = value;
  19816. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19822. /** The default material used on meshes when no material is affected */
  19823. get: function () {
  19824. if (!this._defaultMaterial) {
  19825. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19826. }
  19827. return this._defaultMaterial;
  19828. },
  19829. /** The default material used on meshes when no material is affected */
  19830. set: function (value) {
  19831. this._defaultMaterial = value;
  19832. },
  19833. enumerable: true,
  19834. configurable: true
  19835. });
  19836. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  19837. get: function () {
  19838. return this._texturesEnabled;
  19839. },
  19840. set: function (value) {
  19841. if (this._texturesEnabled === value) {
  19842. return;
  19843. }
  19844. this._texturesEnabled = value;
  19845. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19846. },
  19847. enumerable: true,
  19848. configurable: true
  19849. });
  19850. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  19851. get: function () {
  19852. return this._skeletonsEnabled;
  19853. },
  19854. set: function (value) {
  19855. if (this._skeletonsEnabled === value) {
  19856. return;
  19857. }
  19858. this._skeletonsEnabled = value;
  19859. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  19860. },
  19861. enumerable: true,
  19862. configurable: true
  19863. });
  19864. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  19865. get: function () {
  19866. if (!this._postProcessRenderPipelineManager) {
  19867. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19868. }
  19869. return this._postProcessRenderPipelineManager;
  19870. },
  19871. enumerable: true,
  19872. configurable: true
  19873. });
  19874. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  19875. get: function () {
  19876. if (!this._mainSoundTrack) {
  19877. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19878. }
  19879. return this._mainSoundTrack;
  19880. },
  19881. enumerable: true,
  19882. configurable: true
  19883. });
  19884. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  19885. get: function () {
  19886. return this._alternateRendering;
  19887. },
  19888. enumerable: true,
  19889. configurable: true
  19890. });
  19891. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19892. get: function () {
  19893. return this._frustumPlanes;
  19894. },
  19895. enumerable: true,
  19896. configurable: true
  19897. });
  19898. Object.defineProperty(Scene.prototype, "debugLayer", {
  19899. // Properties
  19900. get: function () {
  19901. if (!this._debugLayer) {
  19902. this._debugLayer = new BABYLON.DebugLayer(this);
  19903. }
  19904. return this._debugLayer;
  19905. },
  19906. enumerable: true,
  19907. configurable: true
  19908. });
  19909. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19910. get: function () {
  19911. return this._workerCollisions;
  19912. },
  19913. set: function (enabled) {
  19914. if (!BABYLON.CollisionCoordinatorLegacy) {
  19915. return;
  19916. }
  19917. enabled = (enabled && !!Worker);
  19918. this._workerCollisions = enabled;
  19919. if (this.collisionCoordinator) {
  19920. this.collisionCoordinator.destroy();
  19921. }
  19922. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19923. this.collisionCoordinator.init(this);
  19924. },
  19925. enumerable: true,
  19926. configurable: true
  19927. });
  19928. Object.defineProperty(Scene.prototype, "selectionOctree", {
  19929. get: function () {
  19930. return this._selectionOctree;
  19931. },
  19932. enumerable: true,
  19933. configurable: true
  19934. });
  19935. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19936. /**
  19937. * The mesh that is currently under the pointer.
  19938. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19939. */
  19940. get: function () {
  19941. return this._pointerOverMesh;
  19942. },
  19943. enumerable: true,
  19944. configurable: true
  19945. });
  19946. Object.defineProperty(Scene.prototype, "pointerX", {
  19947. /**
  19948. * Current on-screen X position of the pointer
  19949. * @return {number} X position of the pointer
  19950. */
  19951. get: function () {
  19952. return this._pointerX;
  19953. },
  19954. enumerable: true,
  19955. configurable: true
  19956. });
  19957. Object.defineProperty(Scene.prototype, "pointerY", {
  19958. /**
  19959. * Current on-screen Y position of the pointer
  19960. * @return {number} Y position of the pointer
  19961. */
  19962. get: function () {
  19963. return this._pointerY;
  19964. },
  19965. enumerable: true,
  19966. configurable: true
  19967. });
  19968. Scene.prototype.getCachedMaterial = function () {
  19969. return this._cachedMaterial;
  19970. };
  19971. Scene.prototype.getCachedEffect = function () {
  19972. return this._cachedEffect;
  19973. };
  19974. Scene.prototype.getCachedVisibility = function () {
  19975. return this._cachedVisibility;
  19976. };
  19977. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  19978. if (visibility === void 0) { visibility = 1; }
  19979. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  19980. };
  19981. Scene.prototype.getBoundingBoxRenderer = function () {
  19982. if (!this._boundingBoxRenderer) {
  19983. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19984. }
  19985. return this._boundingBoxRenderer;
  19986. };
  19987. Scene.prototype.getOutlineRenderer = function () {
  19988. return this._outlineRenderer;
  19989. };
  19990. Scene.prototype.getEngine = function () {
  19991. return this._engine;
  19992. };
  19993. Scene.prototype.getTotalVertices = function () {
  19994. return this._totalVertices.current;
  19995. };
  19996. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19997. get: function () {
  19998. return this._totalVertices;
  19999. },
  20000. enumerable: true,
  20001. configurable: true
  20002. });
  20003. Scene.prototype.getActiveIndices = function () {
  20004. return this._activeIndices.current;
  20005. };
  20006. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20007. get: function () {
  20008. return this._activeIndices;
  20009. },
  20010. enumerable: true,
  20011. configurable: true
  20012. });
  20013. Scene.prototype.getActiveParticles = function () {
  20014. return this._activeParticles.current;
  20015. };
  20016. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20017. get: function () {
  20018. return this._activeParticles;
  20019. },
  20020. enumerable: true,
  20021. configurable: true
  20022. });
  20023. Scene.prototype.getActiveBones = function () {
  20024. return this._activeBones.current;
  20025. };
  20026. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20027. get: function () {
  20028. return this._activeBones;
  20029. },
  20030. enumerable: true,
  20031. configurable: true
  20032. });
  20033. // Stats
  20034. Scene.prototype.getInterFramePerfCounter = function () {
  20035. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20036. return 0;
  20037. };
  20038. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20039. get: function () {
  20040. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20041. return null;
  20042. },
  20043. enumerable: true,
  20044. configurable: true
  20045. });
  20046. Scene.prototype.getLastFrameDuration = function () {
  20047. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20048. return 0;
  20049. };
  20050. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20051. get: function () {
  20052. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20053. return null;
  20054. },
  20055. enumerable: true,
  20056. configurable: true
  20057. });
  20058. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20059. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20060. return 0;
  20061. };
  20062. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20063. get: function () {
  20064. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20065. return null;
  20066. },
  20067. enumerable: true,
  20068. configurable: true
  20069. });
  20070. Scene.prototype.getActiveMeshes = function () {
  20071. return this._activeMeshes;
  20072. };
  20073. Scene.prototype.getRenderTargetsDuration = function () {
  20074. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20075. return 0;
  20076. };
  20077. Scene.prototype.getRenderDuration = function () {
  20078. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20079. return 0;
  20080. };
  20081. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20082. get: function () {
  20083. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20084. return null;
  20085. },
  20086. enumerable: true,
  20087. configurable: true
  20088. });
  20089. Scene.prototype.getParticlesDuration = function () {
  20090. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20091. return 0;
  20092. };
  20093. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20094. get: function () {
  20095. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20096. return null;
  20097. },
  20098. enumerable: true,
  20099. configurable: true
  20100. });
  20101. Scene.prototype.getSpritesDuration = function () {
  20102. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20103. return 0;
  20104. };
  20105. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20106. get: function () {
  20107. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20108. return null;
  20109. },
  20110. enumerable: true,
  20111. configurable: true
  20112. });
  20113. Scene.prototype.getAnimationRatio = function () {
  20114. return this._animationRatio;
  20115. };
  20116. Scene.prototype.getRenderId = function () {
  20117. return this._renderId;
  20118. };
  20119. Scene.prototype.incrementRenderId = function () {
  20120. this._renderId++;
  20121. };
  20122. Scene.prototype._updatePointerPosition = function (evt) {
  20123. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20124. if (!canvasRect) {
  20125. return;
  20126. }
  20127. this._pointerX = evt.clientX - canvasRect.left;
  20128. this._pointerY = evt.clientY - canvasRect.top;
  20129. this._unTranslatedPointerX = this._pointerX;
  20130. this._unTranslatedPointerY = this._pointerY;
  20131. };
  20132. Scene.prototype._createUbo = function () {
  20133. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20134. this._sceneUbo.addUniform("viewProjection", 16);
  20135. this._sceneUbo.addUniform("view", 16);
  20136. };
  20137. Scene.prototype._createAlternateUbo = function () {
  20138. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20139. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20140. this._alternateSceneUbo.addUniform("view", 16);
  20141. };
  20142. // Pointers handling
  20143. /**
  20144. * Use this method to simulate a pointer move on a mesh
  20145. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20146. */
  20147. Scene.prototype.simulatePointerMove = function (pickResult) {
  20148. var evt = new PointerEvent("pointermove");
  20149. return this._processPointerMove(pickResult, evt);
  20150. };
  20151. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20152. var canvas = this._engine.getRenderingCanvas();
  20153. if (!canvas) {
  20154. return this;
  20155. }
  20156. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20157. this.setPointerOverSprite(null);
  20158. this.setPointerOverMesh(pickResult.pickedMesh);
  20159. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20160. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20161. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20162. }
  20163. else {
  20164. canvas.style.cursor = this.hoverCursor;
  20165. }
  20166. }
  20167. else {
  20168. canvas.style.cursor = this.defaultCursor;
  20169. }
  20170. }
  20171. else {
  20172. this.setPointerOverMesh(null);
  20173. // Sprites
  20174. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20175. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20176. this.setPointerOverSprite(pickResult.pickedSprite);
  20177. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20178. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20179. }
  20180. else {
  20181. canvas.style.cursor = this.hoverCursor;
  20182. }
  20183. }
  20184. else {
  20185. this.setPointerOverSprite(null);
  20186. // Restore pointer
  20187. canvas.style.cursor = this.defaultCursor;
  20188. }
  20189. }
  20190. if (pickResult) {
  20191. if (this.onPointerMove) {
  20192. this.onPointerMove(evt, pickResult);
  20193. }
  20194. if (this.onPointerObservable.hasObservers()) {
  20195. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20196. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20197. this.onPointerObservable.notifyObservers(pi, type);
  20198. }
  20199. }
  20200. return this;
  20201. };
  20202. /**
  20203. * Use this method to simulate a pointer down on a mesh
  20204. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20205. */
  20206. Scene.prototype.simulatePointerDown = function (pickResult) {
  20207. var evt = new PointerEvent("pointerdown");
  20208. return this._processPointerDown(pickResult, evt);
  20209. };
  20210. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20211. var _this = this;
  20212. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20213. this._pickedDownMesh = pickResult.pickedMesh;
  20214. var actionManager = pickResult.pickedMesh.actionManager;
  20215. if (actionManager) {
  20216. if (actionManager.hasPickTriggers) {
  20217. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20218. switch (evt.button) {
  20219. case 0:
  20220. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20221. break;
  20222. case 1:
  20223. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20224. break;
  20225. case 2:
  20226. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20227. break;
  20228. }
  20229. }
  20230. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20231. window.setTimeout(function () {
  20232. 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);
  20233. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20234. if (_this._totalPointersPressed !== 0 &&
  20235. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20236. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20237. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20238. _this._startingPointerTime = 0;
  20239. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20240. }
  20241. }
  20242. }, Scene.LongPressDelay);
  20243. }
  20244. }
  20245. }
  20246. if (pickResult) {
  20247. if (this.onPointerDown) {
  20248. this.onPointerDown(evt, pickResult);
  20249. }
  20250. if (this.onPointerObservable.hasObservers()) {
  20251. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20252. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20253. this.onPointerObservable.notifyObservers(pi, type);
  20254. }
  20255. }
  20256. return this;
  20257. };
  20258. /**
  20259. * Use this method to simulate a pointer up on a mesh
  20260. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20261. */
  20262. Scene.prototype.simulatePointerUp = function (pickResult) {
  20263. var evt = new PointerEvent("pointerup");
  20264. var clickInfo = new ClickInfo();
  20265. clickInfo.singleClick = true;
  20266. clickInfo.ignore = true;
  20267. return this._processPointerUp(pickResult, evt, clickInfo);
  20268. };
  20269. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20270. if (pickResult && pickResult && pickResult.pickedMesh) {
  20271. this._pickedUpMesh = pickResult.pickedMesh;
  20272. if (this._pickedDownMesh === this._pickedUpMesh) {
  20273. if (this.onPointerPick) {
  20274. this.onPointerPick(evt, pickResult);
  20275. }
  20276. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20277. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20278. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20279. this.onPointerObservable.notifyObservers(pi, type);
  20280. }
  20281. }
  20282. if (pickResult.pickedMesh.actionManager) {
  20283. if (clickInfo.ignore) {
  20284. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20285. }
  20286. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20287. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20288. }
  20289. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20290. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20291. }
  20292. }
  20293. }
  20294. if (this._pickedDownMesh &&
  20295. this._pickedDownMesh.actionManager &&
  20296. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20297. this._pickedDownMesh !== this._pickedUpMesh) {
  20298. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20299. }
  20300. if (this.onPointerUp) {
  20301. this.onPointerUp(evt, pickResult);
  20302. }
  20303. if (this.onPointerObservable.hasObservers()) {
  20304. if (!clickInfo.ignore) {
  20305. if (!clickInfo.hasSwiped) {
  20306. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20307. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20308. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20309. this.onPointerObservable.notifyObservers(pi, type);
  20310. }
  20311. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20312. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20313. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20314. this.onPointerObservable.notifyObservers(pi, type);
  20315. }
  20316. }
  20317. }
  20318. else {
  20319. var type = BABYLON.PointerEventTypes.POINTERUP;
  20320. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20321. this.onPointerObservable.notifyObservers(pi, type);
  20322. }
  20323. }
  20324. return this;
  20325. };
  20326. /**
  20327. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20328. * @param attachUp defines if you want to attach events to pointerup
  20329. * @param attachDown defines if you want to attach events to pointerdown
  20330. * @param attachMove defines if you want to attach events to pointermove
  20331. */
  20332. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20333. var _this = this;
  20334. if (attachUp === void 0) { attachUp = true; }
  20335. if (attachDown === void 0) { attachDown = true; }
  20336. if (attachMove === void 0) { attachMove = true; }
  20337. this._initActionManager = function (act, clickInfo) {
  20338. if (!_this._meshPickProceed) {
  20339. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20340. _this._currentPickResult = pickResult;
  20341. if (pickResult) {
  20342. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20343. }
  20344. _this._meshPickProceed = true;
  20345. }
  20346. return act;
  20347. };
  20348. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20349. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20350. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20351. btn !== _this._previousButtonPressed) {
  20352. _this._doubleClickOccured = false;
  20353. clickInfo.singleClick = true;
  20354. clickInfo.ignore = false;
  20355. cb(clickInfo, _this._currentPickResult);
  20356. }
  20357. };
  20358. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20359. var clickInfo = new ClickInfo();
  20360. _this._currentPickResult = null;
  20361. var act = null;
  20362. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20363. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20364. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20365. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20366. act = _this._initActionManager(act, clickInfo);
  20367. if (act)
  20368. checkPicking = act.hasPickTriggers;
  20369. }
  20370. if (checkPicking) {
  20371. var btn = evt.button;
  20372. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20373. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20374. if (!clickInfo.hasSwiped) {
  20375. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20376. if (!checkSingleClickImmediately) {
  20377. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20378. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20379. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20380. act = _this._initActionManager(act, clickInfo);
  20381. if (act)
  20382. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20383. }
  20384. }
  20385. if (checkSingleClickImmediately) {
  20386. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20387. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20388. btn !== _this._previousButtonPressed) {
  20389. clickInfo.singleClick = true;
  20390. cb(clickInfo, _this._currentPickResult);
  20391. }
  20392. }
  20393. else {
  20394. // wait that no double click has been raised during the double click delay
  20395. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20396. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20397. }
  20398. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20399. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20400. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20401. act = _this._initActionManager(act, clickInfo);
  20402. if (act)
  20403. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20404. }
  20405. if (checkDoubleClick) {
  20406. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20407. if (btn === _this._previousButtonPressed &&
  20408. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20409. !_this._doubleClickOccured) {
  20410. // pointer has not moved for 2 clicks, it's a double click
  20411. if (!clickInfo.hasSwiped &&
  20412. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20413. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20414. _this._previousStartingPointerTime = 0;
  20415. _this._doubleClickOccured = true;
  20416. clickInfo.doubleClick = true;
  20417. clickInfo.ignore = false;
  20418. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20419. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20420. }
  20421. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20422. cb(clickInfo, _this._currentPickResult);
  20423. }
  20424. else {
  20425. _this._doubleClickOccured = false;
  20426. _this._previousStartingPointerTime = _this._startingPointerTime;
  20427. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20428. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20429. _this._previousButtonPressed = btn;
  20430. if (Scene.ExclusiveDoubleClickMode) {
  20431. if (_this._previousDelayedSimpleClickTimeout) {
  20432. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20433. }
  20434. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20435. cb(clickInfo, _this._previousPickResult);
  20436. }
  20437. else {
  20438. cb(clickInfo, _this._currentPickResult);
  20439. }
  20440. }
  20441. }
  20442. else {
  20443. _this._doubleClickOccured = false;
  20444. _this._previousStartingPointerTime = _this._startingPointerTime;
  20445. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20446. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20447. _this._previousButtonPressed = btn;
  20448. }
  20449. }
  20450. }
  20451. }
  20452. clickInfo.ignore = true;
  20453. cb(clickInfo, _this._currentPickResult);
  20454. };
  20455. this._spritePredicate = function (sprite) {
  20456. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20457. };
  20458. this._onPointerMove = function (evt) {
  20459. _this._updatePointerPosition(evt);
  20460. // PreObservable support
  20461. if (_this.onPrePointerObservable.hasObservers()) {
  20462. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20463. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20464. _this.onPrePointerObservable.notifyObservers(pi, type);
  20465. if (pi.skipOnPointerObservable) {
  20466. return;
  20467. }
  20468. }
  20469. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20470. return;
  20471. }
  20472. if (!_this.pointerMovePredicate) {
  20473. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20474. }
  20475. // Meshes
  20476. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20477. _this._processPointerMove(pickResult, evt);
  20478. };
  20479. this._onPointerDown = function (evt) {
  20480. _this._totalPointersPressed++;
  20481. _this._pickedDownMesh = null;
  20482. _this._meshPickProceed = false;
  20483. _this._updatePointerPosition(evt);
  20484. if (_this.preventDefaultOnPointerDown && canvas) {
  20485. evt.preventDefault();
  20486. canvas.focus();
  20487. }
  20488. // PreObservable support
  20489. if (_this.onPrePointerObservable.hasObservers()) {
  20490. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20491. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20492. _this.onPrePointerObservable.notifyObservers(pi, type);
  20493. if (pi.skipOnPointerObservable) {
  20494. return;
  20495. }
  20496. }
  20497. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20498. return;
  20499. }
  20500. _this._startingPointerPosition.x = _this._pointerX;
  20501. _this._startingPointerPosition.y = _this._pointerY;
  20502. _this._startingPointerTime = new Date().getTime();
  20503. if (!_this.pointerDownPredicate) {
  20504. _this.pointerDownPredicate = function (mesh) {
  20505. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20506. };
  20507. }
  20508. // Meshes
  20509. _this._pickedDownMesh = null;
  20510. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20511. _this._processPointerDown(pickResult, evt);
  20512. // Sprites
  20513. _this._pickedDownSprite = null;
  20514. if (_this.spriteManagers.length > 0) {
  20515. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20516. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20517. if (pickResult.pickedSprite.actionManager) {
  20518. _this._pickedDownSprite = pickResult.pickedSprite;
  20519. switch (evt.button) {
  20520. case 0:
  20521. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20522. break;
  20523. case 1:
  20524. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20525. break;
  20526. case 2:
  20527. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20528. break;
  20529. }
  20530. if (pickResult.pickedSprite.actionManager) {
  20531. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20532. }
  20533. }
  20534. }
  20535. }
  20536. };
  20537. this._onPointerUp = function (evt) {
  20538. if (_this._totalPointersPressed === 0) {
  20539. return; // So we need to test it the pointer down was pressed before.
  20540. }
  20541. _this._totalPointersPressed--;
  20542. _this._pickedUpMesh = null;
  20543. _this._meshPickProceed = false;
  20544. _this._updatePointerPosition(evt);
  20545. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  20546. // PreObservable support
  20547. if (_this.onPrePointerObservable.hasObservers()) {
  20548. if (!clickInfo.ignore) {
  20549. if (!clickInfo.hasSwiped) {
  20550. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20551. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20552. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20553. _this.onPrePointerObservable.notifyObservers(pi, type);
  20554. if (pi.skipOnPointerObservable) {
  20555. return;
  20556. }
  20557. }
  20558. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20559. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20560. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20561. _this.onPrePointerObservable.notifyObservers(pi, type);
  20562. if (pi.skipOnPointerObservable) {
  20563. return;
  20564. }
  20565. }
  20566. }
  20567. }
  20568. else {
  20569. var type = BABYLON.PointerEventTypes.POINTERUP;
  20570. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20571. _this.onPrePointerObservable.notifyObservers(pi, type);
  20572. if (pi.skipOnPointerObservable) {
  20573. return;
  20574. }
  20575. }
  20576. }
  20577. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20578. return;
  20579. }
  20580. if (!_this.pointerUpPredicate) {
  20581. _this.pointerUpPredicate = function (mesh) {
  20582. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20583. };
  20584. }
  20585. // Meshes
  20586. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  20587. _this._initActionManager(null, clickInfo);
  20588. }
  20589. if (!pickResult) {
  20590. pickResult = _this._currentPickResult;
  20591. }
  20592. _this._processPointerUp(pickResult, evt, clickInfo);
  20593. // Sprites
  20594. if (_this.spriteManagers.length > 0) {
  20595. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20596. if (spritePickResult) {
  20597. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  20598. if (spritePickResult.pickedSprite.actionManager) {
  20599. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20600. if (spritePickResult.pickedSprite.actionManager) {
  20601. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  20602. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20603. }
  20604. }
  20605. }
  20606. }
  20607. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  20608. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20609. }
  20610. }
  20611. }
  20612. _this._previousPickResult = _this._currentPickResult;
  20613. });
  20614. };
  20615. this._onKeyDown = function (evt) {
  20616. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  20617. if (_this.onPreKeyboardObservable.hasObservers()) {
  20618. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20619. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20620. if (pi.skipOnPointerObservable) {
  20621. return;
  20622. }
  20623. }
  20624. if (_this.onKeyboardObservable.hasObservers()) {
  20625. var pi = new BABYLON.KeyboardInfo(type, evt);
  20626. _this.onKeyboardObservable.notifyObservers(pi, type);
  20627. }
  20628. if (_this.actionManager) {
  20629. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20630. }
  20631. };
  20632. this._onKeyUp = function (evt) {
  20633. var type = BABYLON.KeyboardEventTypes.KEYUP;
  20634. if (_this.onPreKeyboardObservable.hasObservers()) {
  20635. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20636. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20637. if (pi.skipOnPointerObservable) {
  20638. return;
  20639. }
  20640. }
  20641. if (_this.onKeyboardObservable.hasObservers()) {
  20642. var pi = new BABYLON.KeyboardInfo(type, evt);
  20643. _this.onKeyboardObservable.notifyObservers(pi, type);
  20644. }
  20645. if (_this.actionManager) {
  20646. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20647. }
  20648. };
  20649. var engine = this.getEngine();
  20650. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  20651. if (!canvas) {
  20652. return;
  20653. }
  20654. canvas.addEventListener("keydown", _this._onKeyDown, false);
  20655. canvas.addEventListener("keyup", _this._onKeyUp, false);
  20656. });
  20657. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  20658. if (!canvas) {
  20659. return;
  20660. }
  20661. canvas.removeEventListener("keydown", _this._onKeyDown);
  20662. canvas.removeEventListener("keyup", _this._onKeyUp);
  20663. });
  20664. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20665. var canvas = this._engine.getRenderingCanvas();
  20666. if (!canvas) {
  20667. return;
  20668. }
  20669. if (attachMove) {
  20670. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20671. // Wheel
  20672. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20673. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20674. }
  20675. if (attachDown) {
  20676. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20677. }
  20678. if (attachUp) {
  20679. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20680. }
  20681. canvas.tabIndex = 1;
  20682. };
  20683. Scene.prototype.detachControl = function () {
  20684. var engine = this.getEngine();
  20685. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20686. var canvas = engine.getRenderingCanvas();
  20687. if (!canvas) {
  20688. return;
  20689. }
  20690. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20691. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20692. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20693. if (this._onCanvasBlurObserver) {
  20694. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  20695. }
  20696. if (this._onCanvasFocusObserver) {
  20697. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  20698. }
  20699. // Wheel
  20700. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20701. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20702. // Keyboard
  20703. canvas.removeEventListener("keydown", this._onKeyDown);
  20704. canvas.removeEventListener("keyup", this._onKeyUp);
  20705. // Observables
  20706. this.onKeyboardObservable.clear();
  20707. this.onPreKeyboardObservable.clear();
  20708. this.onPointerObservable.clear();
  20709. this.onPrePointerObservable.clear();
  20710. };
  20711. /**
  20712. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  20713. * Delay loaded resources are not taking in account
  20714. * @return true if all required resources are ready
  20715. */
  20716. Scene.prototype.isReady = function () {
  20717. if (this._isDisposed) {
  20718. return false;
  20719. }
  20720. if (this._pendingData.length > 0) {
  20721. return false;
  20722. }
  20723. var index;
  20724. var engine = this.getEngine();
  20725. // Geometries
  20726. for (index = 0; index < this._geometries.length; index++) {
  20727. var geometry = this._geometries[index];
  20728. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20729. return false;
  20730. }
  20731. }
  20732. // Meshes
  20733. for (index = 0; index < this.meshes.length; index++) {
  20734. var mesh = this.meshes[index];
  20735. if (!mesh.isEnabled()) {
  20736. continue;
  20737. }
  20738. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  20739. continue;
  20740. }
  20741. if (!mesh.isReady()) {
  20742. return false;
  20743. }
  20744. // Highlight layers
  20745. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  20746. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  20747. var layer = _a[_i];
  20748. if (!layer.hasMesh(mesh)) {
  20749. continue;
  20750. }
  20751. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  20752. var subMesh = _c[_b];
  20753. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  20754. return false;
  20755. }
  20756. }
  20757. }
  20758. }
  20759. return true;
  20760. };
  20761. Scene.prototype.resetCachedMaterial = function () {
  20762. this._cachedMaterial = null;
  20763. this._cachedEffect = null;
  20764. this._cachedVisibility = null;
  20765. };
  20766. Scene.prototype.registerBeforeRender = function (func) {
  20767. this.onBeforeRenderObservable.add(func);
  20768. };
  20769. Scene.prototype.unregisterBeforeRender = function (func) {
  20770. this.onBeforeRenderObservable.removeCallback(func);
  20771. };
  20772. Scene.prototype.registerAfterRender = function (func) {
  20773. this.onAfterRenderObservable.add(func);
  20774. };
  20775. Scene.prototype.unregisterAfterRender = function (func) {
  20776. this.onAfterRenderObservable.removeCallback(func);
  20777. };
  20778. Scene.prototype._executeOnceBeforeRender = function (func) {
  20779. var _this = this;
  20780. var execFunc = function () {
  20781. func();
  20782. setTimeout(function () {
  20783. _this.unregisterBeforeRender(execFunc);
  20784. });
  20785. };
  20786. this.registerBeforeRender(execFunc);
  20787. };
  20788. /**
  20789. * The provided function will run before render once and will be disposed afterwards.
  20790. * A timeout delay can be provided so that the function will be executed in N ms.
  20791. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  20792. * @param func The function to be executed.
  20793. * @param timeout optional delay in ms
  20794. */
  20795. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  20796. var _this = this;
  20797. if (timeout !== undefined) {
  20798. setTimeout(function () {
  20799. _this._executeOnceBeforeRender(func);
  20800. }, timeout);
  20801. }
  20802. else {
  20803. this._executeOnceBeforeRender(func);
  20804. }
  20805. };
  20806. Scene.prototype._addPendingData = function (data) {
  20807. this._pendingData.push(data);
  20808. };
  20809. Scene.prototype._removePendingData = function (data) {
  20810. var wasLoading = this.isLoading;
  20811. var index = this._pendingData.indexOf(data);
  20812. if (index !== -1) {
  20813. this._pendingData.splice(index, 1);
  20814. }
  20815. if (wasLoading && !this.isLoading) {
  20816. this.onDataLoadedObservable.notifyObservers(this);
  20817. }
  20818. };
  20819. Scene.prototype.getWaitingItemsCount = function () {
  20820. return this._pendingData.length;
  20821. };
  20822. Object.defineProperty(Scene.prototype, "isLoading", {
  20823. get: function () {
  20824. return this._pendingData.length > 0;
  20825. },
  20826. enumerable: true,
  20827. configurable: true
  20828. });
  20829. /**
  20830. * Registers a function to be executed when the scene is ready.
  20831. * @param {Function} func - the function to be executed.
  20832. */
  20833. Scene.prototype.executeWhenReady = function (func) {
  20834. var _this = this;
  20835. this.onReadyObservable.add(func);
  20836. if (this._executeWhenReadyTimeoutId !== -1) {
  20837. return;
  20838. }
  20839. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20840. _this._checkIsReady();
  20841. }, 150);
  20842. };
  20843. Scene.prototype._checkIsReady = function () {
  20844. var _this = this;
  20845. if (this.isReady()) {
  20846. this.onReadyObservable.notifyObservers(this);
  20847. this.onReadyObservable.clear();
  20848. this._executeWhenReadyTimeoutId = -1;
  20849. return;
  20850. }
  20851. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20852. _this._checkIsReady();
  20853. }, 150);
  20854. };
  20855. // Animations
  20856. /**
  20857. * Will start the animation sequence of a given target
  20858. * @param target - the target
  20859. * @param {number} from - from which frame should animation start
  20860. * @param {number} to - till which frame should animation run.
  20861. * @param {boolean} [loop] - should the animation loop
  20862. * @param {number} [speedRatio] - the speed in which to run the animation
  20863. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20864. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20865. * Returns {BABYLON.Animatable} the animatable object created for this animation
  20866. * See BABYLON.Animatable
  20867. */
  20868. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20869. if (speedRatio === void 0) { speedRatio = 1.0; }
  20870. if (from > to && speedRatio > 0) {
  20871. speedRatio *= -1;
  20872. }
  20873. this.stopAnimation(target);
  20874. if (!animatable) {
  20875. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20876. }
  20877. // Local animations
  20878. if (target.animations) {
  20879. animatable.appendAnimations(target, target.animations);
  20880. }
  20881. // Children animations
  20882. if (target.getAnimatables) {
  20883. var animatables = target.getAnimatables();
  20884. for (var index = 0; index < animatables.length; index++) {
  20885. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20886. }
  20887. }
  20888. animatable.reset();
  20889. return animatable;
  20890. };
  20891. /**
  20892. * Begin a new animation on a given node
  20893. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20894. * @param {BABYLON.Animation[]} defines the list of animations to start
  20895. * @param {number} from defines the initial value
  20896. * @param {number} to defines the final value
  20897. * @param {boolean} loop defines if you want animation to loop (off by default)
  20898. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20899. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20900. * @returns the list of created animatables
  20901. */
  20902. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20903. if (speedRatio === undefined) {
  20904. speedRatio = 1.0;
  20905. }
  20906. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20907. return animatable;
  20908. };
  20909. /**
  20910. * Begin a new animation on a given node and its hierarchy
  20911. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20912. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  20913. * @param {BABYLON.Animation[]} defines the list of animations to start
  20914. * @param {number} from defines the initial value
  20915. * @param {number} to defines the final value
  20916. * @param {boolean} loop defines if you want animation to loop (off by default)
  20917. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20918. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20919. * @returns the list of animatables created for all nodes
  20920. */
  20921. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20922. var children = target.getDescendants(directDescendantsOnly);
  20923. var result = [];
  20924. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  20925. var child = children_1[_i];
  20926. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  20927. }
  20928. return result;
  20929. };
  20930. Scene.prototype.getAnimatableByTarget = function (target) {
  20931. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20932. if (this._activeAnimatables[index].target === target) {
  20933. return this._activeAnimatables[index];
  20934. }
  20935. }
  20936. return null;
  20937. };
  20938. Object.defineProperty(Scene.prototype, "animatables", {
  20939. get: function () {
  20940. return this._activeAnimatables;
  20941. },
  20942. enumerable: true,
  20943. configurable: true
  20944. });
  20945. /**
  20946. * Will stop the animation of the given target
  20947. * @param target - the target
  20948. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20949. * @see beginAnimation
  20950. */
  20951. Scene.prototype.stopAnimation = function (target, animationName) {
  20952. var animatable = this.getAnimatableByTarget(target);
  20953. if (animatable) {
  20954. animatable.stop(animationName);
  20955. }
  20956. };
  20957. /**
  20958. * Stops and removes all animations that have been applied to the scene
  20959. */
  20960. Scene.prototype.stopAllAnimations = function () {
  20961. if (this._activeAnimatables) {
  20962. for (var i = 0; i < this._activeAnimatables.length; i++) {
  20963. this._activeAnimatables[i].stop();
  20964. }
  20965. this._activeAnimatables = [];
  20966. }
  20967. };
  20968. Scene.prototype._animate = function () {
  20969. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20970. return;
  20971. }
  20972. // Getting time
  20973. var now = BABYLON.Tools.Now;
  20974. if (!this._animationTimeLast) {
  20975. if (this._pendingData.length > 0) {
  20976. return;
  20977. }
  20978. this._animationTimeLast = now;
  20979. }
  20980. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  20981. this._animationTime += deltaTime;
  20982. this._animationTimeLast = now;
  20983. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20984. this._activeAnimatables[index]._animate(this._animationTime);
  20985. }
  20986. };
  20987. // Matrix
  20988. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  20989. this._useAlternateCameraConfiguration = active;
  20990. };
  20991. Scene.prototype.getViewMatrix = function () {
  20992. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  20993. };
  20994. Scene.prototype.getProjectionMatrix = function () {
  20995. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  20996. };
  20997. Scene.prototype.getTransformMatrix = function () {
  20998. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  20999. };
  21000. Scene.prototype.setTransformMatrix = function (view, projection) {
  21001. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21002. return;
  21003. }
  21004. this._viewUpdateFlag = view.updateFlag;
  21005. this._projectionUpdateFlag = projection.updateFlag;
  21006. this._viewMatrix = view;
  21007. this._projectionMatrix = projection;
  21008. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21009. // Update frustum
  21010. if (!this._frustumPlanes) {
  21011. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21012. }
  21013. else {
  21014. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21015. }
  21016. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21017. var otherCamera = this.activeCamera._alternateCamera;
  21018. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21019. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21020. }
  21021. if (this._sceneUbo.useUbo) {
  21022. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21023. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21024. this._sceneUbo.update();
  21025. }
  21026. };
  21027. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21028. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21029. return;
  21030. }
  21031. this._alternateViewUpdateFlag = view.updateFlag;
  21032. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21033. this._alternateViewMatrix = view;
  21034. this._alternateProjectionMatrix = projection;
  21035. if (!this._alternateTransformMatrix) {
  21036. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21037. }
  21038. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21039. if (!this._alternateSceneUbo) {
  21040. this._createAlternateUbo();
  21041. }
  21042. if (this._alternateSceneUbo.useUbo) {
  21043. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21044. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21045. this._alternateSceneUbo.update();
  21046. }
  21047. };
  21048. Scene.prototype.getSceneUniformBuffer = function () {
  21049. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21050. };
  21051. // Methods
  21052. Scene.prototype.getUniqueId = function () {
  21053. var result = Scene._uniqueIdCounter;
  21054. Scene._uniqueIdCounter++;
  21055. return result;
  21056. };
  21057. Scene.prototype.addMesh = function (newMesh) {
  21058. this.meshes.push(newMesh);
  21059. //notify the collision coordinator
  21060. if (this.collisionCoordinator) {
  21061. this.collisionCoordinator.onMeshAdded(newMesh);
  21062. }
  21063. newMesh._resyncLightSources();
  21064. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21065. };
  21066. Scene.prototype.removeMesh = function (toRemove) {
  21067. var index = this.meshes.indexOf(toRemove);
  21068. if (index !== -1) {
  21069. // Remove from the scene if mesh found
  21070. this.meshes.splice(index, 1);
  21071. }
  21072. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21073. return index;
  21074. };
  21075. Scene.prototype.addTransformNode = function (newTransformNode) {
  21076. this.transformNodes.push(newTransformNode);
  21077. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21078. };
  21079. Scene.prototype.removeTransformNode = function (toRemove) {
  21080. var index = this.transformNodes.indexOf(toRemove);
  21081. if (index !== -1) {
  21082. // Remove from the scene if found
  21083. this.transformNodes.splice(index, 1);
  21084. }
  21085. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21086. return index;
  21087. };
  21088. Scene.prototype.removeSkeleton = function (toRemove) {
  21089. var index = this.skeletons.indexOf(toRemove);
  21090. if (index !== -1) {
  21091. // Remove from the scene if found
  21092. this.skeletons.splice(index, 1);
  21093. }
  21094. return index;
  21095. };
  21096. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21097. var index = this.morphTargetManagers.indexOf(toRemove);
  21098. if (index !== -1) {
  21099. // Remove from the scene if found
  21100. this.morphTargetManagers.splice(index, 1);
  21101. }
  21102. return index;
  21103. };
  21104. Scene.prototype.removeLight = function (toRemove) {
  21105. var index = this.lights.indexOf(toRemove);
  21106. if (index !== -1) {
  21107. // Remove from meshes
  21108. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21109. var mesh = _a[_i];
  21110. mesh._removeLightSource(toRemove);
  21111. }
  21112. // Remove from the scene if mesh found
  21113. this.lights.splice(index, 1);
  21114. this.sortLightsByPriority();
  21115. }
  21116. this.onLightRemovedObservable.notifyObservers(toRemove);
  21117. return index;
  21118. };
  21119. Scene.prototype.removeCamera = function (toRemove) {
  21120. var index = this.cameras.indexOf(toRemove);
  21121. if (index !== -1) {
  21122. // Remove from the scene if mesh found
  21123. this.cameras.splice(index, 1);
  21124. }
  21125. // Remove from activeCameras
  21126. var index2 = this.activeCameras.indexOf(toRemove);
  21127. if (index2 !== -1) {
  21128. // Remove from the scene if mesh found
  21129. this.activeCameras.splice(index2, 1);
  21130. }
  21131. // Reset the activeCamera
  21132. if (this.activeCamera === toRemove) {
  21133. if (this.cameras.length > 0) {
  21134. this.activeCamera = this.cameras[0];
  21135. }
  21136. else {
  21137. this.activeCamera = null;
  21138. }
  21139. }
  21140. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21141. return index;
  21142. };
  21143. Scene.prototype.removeParticleSystem = function (toRemove) {
  21144. var index = this.particleSystems.indexOf(toRemove);
  21145. if (index !== -1) {
  21146. this.particleSystems.splice(index, 1);
  21147. }
  21148. return index;
  21149. };
  21150. ;
  21151. Scene.prototype.removeAnimation = function (toRemove) {
  21152. var index = this.animations.indexOf(toRemove);
  21153. if (index !== -1) {
  21154. this.animations.splice(index, 1);
  21155. }
  21156. return index;
  21157. };
  21158. ;
  21159. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21160. var index = this.multiMaterials.indexOf(toRemove);
  21161. if (index !== -1) {
  21162. this.multiMaterials.splice(index, 1);
  21163. }
  21164. return index;
  21165. };
  21166. ;
  21167. Scene.prototype.removeMaterial = function (toRemove) {
  21168. var index = this.materials.indexOf(toRemove);
  21169. if (index !== -1) {
  21170. this.materials.splice(index, 1);
  21171. }
  21172. return index;
  21173. };
  21174. ;
  21175. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21176. var index = this.lensFlareSystems.indexOf(toRemove);
  21177. if (index !== -1) {
  21178. this.lensFlareSystems.splice(index, 1);
  21179. }
  21180. return index;
  21181. };
  21182. ;
  21183. Scene.prototype.removeActionManager = function (toRemove) {
  21184. var index = this._actionManagers.indexOf(toRemove);
  21185. if (index !== -1) {
  21186. this._actionManagers.splice(index, 1);
  21187. }
  21188. return index;
  21189. };
  21190. ;
  21191. Scene.prototype.addLight = function (newLight) {
  21192. this.lights.push(newLight);
  21193. this.sortLightsByPriority();
  21194. // Add light to all meshes (To support if the light is removed and then readded)
  21195. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21196. var mesh = _a[_i];
  21197. if (mesh._lightSources.indexOf(newLight) === -1) {
  21198. mesh._lightSources.push(newLight);
  21199. mesh._resyncLightSources();
  21200. }
  21201. }
  21202. this.onNewLightAddedObservable.notifyObservers(newLight);
  21203. };
  21204. Scene.prototype.sortLightsByPriority = function () {
  21205. if (this.requireLightSorting) {
  21206. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21207. }
  21208. };
  21209. Scene.prototype.addCamera = function (newCamera) {
  21210. this.cameras.push(newCamera);
  21211. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21212. };
  21213. Scene.prototype.addSkeleton = function (newSkeleton) {
  21214. this.skeletons.push(newSkeleton);
  21215. };
  21216. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21217. this.particleSystems.push(newParticleSystem);
  21218. };
  21219. Scene.prototype.addAnimation = function (newAnimation) {
  21220. this.animations.push(newAnimation);
  21221. };
  21222. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21223. this.multiMaterials.push(newMultiMaterial);
  21224. };
  21225. Scene.prototype.addMaterial = function (newMaterial) {
  21226. this.materials.push(newMaterial);
  21227. };
  21228. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21229. this.morphTargetManagers.push(newMorphTargetManager);
  21230. };
  21231. Scene.prototype.addGeometry = function (newGeometrie) {
  21232. this._geometries.push(newGeometrie);
  21233. };
  21234. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21235. this.lensFlareSystems.push(newLensFlareSystem);
  21236. };
  21237. Scene.prototype.addActionManager = function (newActionManager) {
  21238. this._actionManagers.push(newActionManager);
  21239. };
  21240. /**
  21241. * Switch active camera
  21242. * @param {Camera} newCamera - new active camera
  21243. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21244. */
  21245. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21246. if (attachControl === void 0) { attachControl = true; }
  21247. var canvas = this._engine.getRenderingCanvas();
  21248. if (!canvas) {
  21249. return;
  21250. }
  21251. if (this.activeCamera) {
  21252. this.activeCamera.detachControl(canvas);
  21253. }
  21254. this.activeCamera = newCamera;
  21255. if (attachControl) {
  21256. newCamera.attachControl(canvas);
  21257. }
  21258. };
  21259. /**
  21260. * sets the active camera of the scene using its ID
  21261. * @param {string} id - the camera's ID
  21262. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21263. * @see activeCamera
  21264. */
  21265. Scene.prototype.setActiveCameraByID = function (id) {
  21266. var camera = this.getCameraByID(id);
  21267. if (camera) {
  21268. this.activeCamera = camera;
  21269. return camera;
  21270. }
  21271. return null;
  21272. };
  21273. /**
  21274. * sets the active camera of the scene using its name
  21275. * @param {string} name - the camera's name
  21276. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21277. * @see activeCamera
  21278. */
  21279. Scene.prototype.setActiveCameraByName = function (name) {
  21280. var camera = this.getCameraByName(name);
  21281. if (camera) {
  21282. this.activeCamera = camera;
  21283. return camera;
  21284. }
  21285. return null;
  21286. };
  21287. /**
  21288. * get an animation group using its name
  21289. * @param {string} the material's name
  21290. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21291. */
  21292. Scene.prototype.getAnimationGroupByName = function (name) {
  21293. for (var index = 0; index < this.animationGroups.length; index++) {
  21294. if (this.animationGroups[index].name === name) {
  21295. return this.animationGroups[index];
  21296. }
  21297. }
  21298. return null;
  21299. };
  21300. /**
  21301. * get a material using its id
  21302. * @param {string} the material's ID
  21303. * @return {BABYLON.Material|null} the material or null if none found.
  21304. */
  21305. Scene.prototype.getMaterialByID = function (id) {
  21306. for (var index = 0; index < this.materials.length; index++) {
  21307. if (this.materials[index].id === id) {
  21308. return this.materials[index];
  21309. }
  21310. }
  21311. return null;
  21312. };
  21313. /**
  21314. * get a material using its name
  21315. * @param {string} the material's name
  21316. * @return {BABYLON.Material|null} the material or null if none found.
  21317. */
  21318. Scene.prototype.getMaterialByName = function (name) {
  21319. for (var index = 0; index < this.materials.length; index++) {
  21320. if (this.materials[index].name === name) {
  21321. return this.materials[index];
  21322. }
  21323. }
  21324. return null;
  21325. };
  21326. Scene.prototype.getLensFlareSystemByName = function (name) {
  21327. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21328. if (this.lensFlareSystems[index].name === name) {
  21329. return this.lensFlareSystems[index];
  21330. }
  21331. }
  21332. return null;
  21333. };
  21334. Scene.prototype.getLensFlareSystemByID = function (id) {
  21335. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21336. if (this.lensFlareSystems[index].id === id) {
  21337. return this.lensFlareSystems[index];
  21338. }
  21339. }
  21340. return null;
  21341. };
  21342. Scene.prototype.getCameraByID = function (id) {
  21343. for (var index = 0; index < this.cameras.length; index++) {
  21344. if (this.cameras[index].id === id) {
  21345. return this.cameras[index];
  21346. }
  21347. }
  21348. return null;
  21349. };
  21350. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21351. for (var index = 0; index < this.cameras.length; index++) {
  21352. if (this.cameras[index].uniqueId === uniqueId) {
  21353. return this.cameras[index];
  21354. }
  21355. }
  21356. return null;
  21357. };
  21358. /**
  21359. * get a camera using its name
  21360. * @param {string} the camera's name
  21361. * @return {BABYLON.Camera|null} the camera or null if none found.
  21362. */
  21363. Scene.prototype.getCameraByName = function (name) {
  21364. for (var index = 0; index < this.cameras.length; index++) {
  21365. if (this.cameras[index].name === name) {
  21366. return this.cameras[index];
  21367. }
  21368. }
  21369. return null;
  21370. };
  21371. /**
  21372. * get a bone using its id
  21373. * @param {string} the bone's id
  21374. * @return {BABYLON.Bone|null} the bone or null if not found
  21375. */
  21376. Scene.prototype.getBoneByID = function (id) {
  21377. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21378. var skeleton = this.skeletons[skeletonIndex];
  21379. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21380. if (skeleton.bones[boneIndex].id === id) {
  21381. return skeleton.bones[boneIndex];
  21382. }
  21383. }
  21384. }
  21385. return null;
  21386. };
  21387. /**
  21388. * get a bone using its id
  21389. * @param {string} the bone's name
  21390. * @return {BABYLON.Bone|null} the bone or null if not found
  21391. */
  21392. Scene.prototype.getBoneByName = function (name) {
  21393. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21394. var skeleton = this.skeletons[skeletonIndex];
  21395. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21396. if (skeleton.bones[boneIndex].name === name) {
  21397. return skeleton.bones[boneIndex];
  21398. }
  21399. }
  21400. }
  21401. return null;
  21402. };
  21403. /**
  21404. * get a light node using its name
  21405. * @param {string} the light's name
  21406. * @return {BABYLON.Light|null} the light or null if none found.
  21407. */
  21408. Scene.prototype.getLightByName = function (name) {
  21409. for (var index = 0; index < this.lights.length; index++) {
  21410. if (this.lights[index].name === name) {
  21411. return this.lights[index];
  21412. }
  21413. }
  21414. return null;
  21415. };
  21416. /**
  21417. * get a light node using its ID
  21418. * @param {string} the light's id
  21419. * @return {BABYLON.Light|null} the light or null if none found.
  21420. */
  21421. Scene.prototype.getLightByID = function (id) {
  21422. for (var index = 0; index < this.lights.length; index++) {
  21423. if (this.lights[index].id === id) {
  21424. return this.lights[index];
  21425. }
  21426. }
  21427. return null;
  21428. };
  21429. /**
  21430. * get a light node using its scene-generated unique ID
  21431. * @param {number} the light's unique id
  21432. * @return {BABYLON.Light|null} the light or null if none found.
  21433. */
  21434. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21435. for (var index = 0; index < this.lights.length; index++) {
  21436. if (this.lights[index].uniqueId === uniqueId) {
  21437. return this.lights[index];
  21438. }
  21439. }
  21440. return null;
  21441. };
  21442. /**
  21443. * get a particle system by id
  21444. * @param id {number} the particle system id
  21445. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  21446. */
  21447. Scene.prototype.getParticleSystemByID = function (id) {
  21448. for (var index = 0; index < this.particleSystems.length; index++) {
  21449. if (this.particleSystems[index].id === id) {
  21450. return this.particleSystems[index];
  21451. }
  21452. }
  21453. return null;
  21454. };
  21455. /**
  21456. * get a geometry using its ID
  21457. * @param {string} the geometry's id
  21458. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21459. */
  21460. Scene.prototype.getGeometryByID = function (id) {
  21461. for (var index = 0; index < this._geometries.length; index++) {
  21462. if (this._geometries[index].id === id) {
  21463. return this._geometries[index];
  21464. }
  21465. }
  21466. return null;
  21467. };
  21468. /**
  21469. * add a new geometry to this scene.
  21470. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21471. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21472. * @return {boolean} was the geometry added or not
  21473. */
  21474. Scene.prototype.pushGeometry = function (geometry, force) {
  21475. if (!force && this.getGeometryByID(geometry.id)) {
  21476. return false;
  21477. }
  21478. this._geometries.push(geometry);
  21479. //notify the collision coordinator
  21480. if (this.collisionCoordinator) {
  21481. this.collisionCoordinator.onGeometryAdded(geometry);
  21482. }
  21483. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21484. return true;
  21485. };
  21486. /**
  21487. * Removes an existing geometry
  21488. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21489. * @return {boolean} was the geometry removed or not
  21490. */
  21491. Scene.prototype.removeGeometry = function (geometry) {
  21492. var index = this._geometries.indexOf(geometry);
  21493. if (index > -1) {
  21494. this._geometries.splice(index, 1);
  21495. //notify the collision coordinator
  21496. if (this.collisionCoordinator) {
  21497. this.collisionCoordinator.onGeometryDeleted(geometry);
  21498. }
  21499. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21500. return true;
  21501. }
  21502. return false;
  21503. };
  21504. Scene.prototype.getGeometries = function () {
  21505. return this._geometries;
  21506. };
  21507. /**
  21508. * Get the first added mesh found of a given ID
  21509. * @param {string} id - the id to search for
  21510. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21511. */
  21512. Scene.prototype.getMeshByID = function (id) {
  21513. for (var index = 0; index < this.meshes.length; index++) {
  21514. if (this.meshes[index].id === id) {
  21515. return this.meshes[index];
  21516. }
  21517. }
  21518. return null;
  21519. };
  21520. Scene.prototype.getMeshesByID = function (id) {
  21521. return this.meshes.filter(function (m) {
  21522. return m.id === id;
  21523. });
  21524. };
  21525. /**
  21526. * Get the first added transform node found of a given ID
  21527. * @param {string} id - the id to search for
  21528. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  21529. */
  21530. Scene.prototype.getTransformNodeByID = function (id) {
  21531. for (var index = 0; index < this.transformNodes.length; index++) {
  21532. if (this.transformNodes[index].id === id) {
  21533. return this.transformNodes[index];
  21534. }
  21535. }
  21536. return null;
  21537. };
  21538. Scene.prototype.getTransformNodesByID = function (id) {
  21539. return this.transformNodes.filter(function (m) {
  21540. return m.id === id;
  21541. });
  21542. };
  21543. /**
  21544. * Get a mesh with its auto-generated unique id
  21545. * @param {number} uniqueId - the unique id to search for
  21546. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21547. */
  21548. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21549. for (var index = 0; index < this.meshes.length; index++) {
  21550. if (this.meshes[index].uniqueId === uniqueId) {
  21551. return this.meshes[index];
  21552. }
  21553. }
  21554. return null;
  21555. };
  21556. /**
  21557. * Get a the last added mesh found of a given ID
  21558. * @param {string} id - the id to search for
  21559. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21560. */
  21561. Scene.prototype.getLastMeshByID = function (id) {
  21562. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21563. if (this.meshes[index].id === id) {
  21564. return this.meshes[index];
  21565. }
  21566. }
  21567. return null;
  21568. };
  21569. /**
  21570. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21571. * @param {string} id - the id to search for
  21572. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21573. */
  21574. Scene.prototype.getLastEntryByID = function (id) {
  21575. var index;
  21576. for (index = this.meshes.length - 1; index >= 0; index--) {
  21577. if (this.meshes[index].id === id) {
  21578. return this.meshes[index];
  21579. }
  21580. }
  21581. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  21582. if (this.transformNodes[index].id === id) {
  21583. return this.transformNodes[index];
  21584. }
  21585. }
  21586. for (index = this.cameras.length - 1; index >= 0; index--) {
  21587. if (this.cameras[index].id === id) {
  21588. return this.cameras[index];
  21589. }
  21590. }
  21591. for (index = this.lights.length - 1; index >= 0; index--) {
  21592. if (this.lights[index].id === id) {
  21593. return this.lights[index];
  21594. }
  21595. }
  21596. return null;
  21597. };
  21598. Scene.prototype.getNodeByID = function (id) {
  21599. var mesh = this.getMeshByID(id);
  21600. if (mesh) {
  21601. return mesh;
  21602. }
  21603. var light = this.getLightByID(id);
  21604. if (light) {
  21605. return light;
  21606. }
  21607. var camera = this.getCameraByID(id);
  21608. if (camera) {
  21609. return camera;
  21610. }
  21611. var bone = this.getBoneByID(id);
  21612. return bone;
  21613. };
  21614. Scene.prototype.getNodeByName = function (name) {
  21615. var mesh = this.getMeshByName(name);
  21616. if (mesh) {
  21617. return mesh;
  21618. }
  21619. var light = this.getLightByName(name);
  21620. if (light) {
  21621. return light;
  21622. }
  21623. var camera = this.getCameraByName(name);
  21624. if (camera) {
  21625. return camera;
  21626. }
  21627. var bone = this.getBoneByName(name);
  21628. return bone;
  21629. };
  21630. Scene.prototype.getMeshByName = function (name) {
  21631. for (var index = 0; index < this.meshes.length; index++) {
  21632. if (this.meshes[index].name === name) {
  21633. return this.meshes[index];
  21634. }
  21635. }
  21636. return null;
  21637. };
  21638. Scene.prototype.getTransformNodeByName = function (name) {
  21639. for (var index = 0; index < this.transformNodes.length; index++) {
  21640. if (this.transformNodes[index].name === name) {
  21641. return this.transformNodes[index];
  21642. }
  21643. }
  21644. return null;
  21645. };
  21646. Scene.prototype.getSoundByName = function (name) {
  21647. var index;
  21648. if (BABYLON.AudioEngine) {
  21649. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21650. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21651. return this.mainSoundTrack.soundCollection[index];
  21652. }
  21653. }
  21654. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21655. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21656. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21657. return this.soundTracks[sdIndex].soundCollection[index];
  21658. }
  21659. }
  21660. }
  21661. }
  21662. return null;
  21663. };
  21664. Scene.prototype.getLastSkeletonByID = function (id) {
  21665. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21666. if (this.skeletons[index].id === id) {
  21667. return this.skeletons[index];
  21668. }
  21669. }
  21670. return null;
  21671. };
  21672. Scene.prototype.getSkeletonById = function (id) {
  21673. for (var index = 0; index < this.skeletons.length; index++) {
  21674. if (this.skeletons[index].id === id) {
  21675. return this.skeletons[index];
  21676. }
  21677. }
  21678. return null;
  21679. };
  21680. Scene.prototype.getSkeletonByName = function (name) {
  21681. for (var index = 0; index < this.skeletons.length; index++) {
  21682. if (this.skeletons[index].name === name) {
  21683. return this.skeletons[index];
  21684. }
  21685. }
  21686. return null;
  21687. };
  21688. Scene.prototype.getMorphTargetManagerById = function (id) {
  21689. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  21690. if (this.morphTargetManagers[index].uniqueId === id) {
  21691. return this.morphTargetManagers[index];
  21692. }
  21693. }
  21694. return null;
  21695. };
  21696. Scene.prototype.isActiveMesh = function (mesh) {
  21697. return (this._activeMeshes.indexOf(mesh) !== -1);
  21698. };
  21699. /**
  21700. * Return a the first highlight layer of the scene with a given name.
  21701. * @param name The name of the highlight layer to look for.
  21702. * @return The highlight layer if found otherwise null.
  21703. */
  21704. Scene.prototype.getHighlightLayerByName = function (name) {
  21705. for (var index = 0; index < this.highlightLayers.length; index++) {
  21706. if (this.highlightLayers[index].name === name) {
  21707. return this.highlightLayers[index];
  21708. }
  21709. }
  21710. return null;
  21711. };
  21712. Object.defineProperty(Scene.prototype, "uid", {
  21713. /**
  21714. * Return a unique id as a string which can serve as an identifier for the scene
  21715. */
  21716. get: function () {
  21717. if (!this._uid) {
  21718. this._uid = BABYLON.Tools.RandomId();
  21719. }
  21720. return this._uid;
  21721. },
  21722. enumerable: true,
  21723. configurable: true
  21724. });
  21725. /**
  21726. * Add an externaly attached data from its key.
  21727. * This method call will fail and return false, if such key already exists.
  21728. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21729. * @param key the unique key that identifies the data
  21730. * @param data the data object to associate to the key for this Engine instance
  21731. * @return true if no such key were already present and the data was added successfully, false otherwise
  21732. */
  21733. Scene.prototype.addExternalData = function (key, data) {
  21734. if (!this._externalData) {
  21735. this._externalData = new BABYLON.StringDictionary();
  21736. }
  21737. return this._externalData.add(key, data);
  21738. };
  21739. /**
  21740. * Get an externaly attached data from its key
  21741. * @param key the unique key that identifies the data
  21742. * @return the associated data, if present (can be null), or undefined if not present
  21743. */
  21744. Scene.prototype.getExternalData = function (key) {
  21745. if (!this._externalData) {
  21746. return null;
  21747. }
  21748. return this._externalData.get(key);
  21749. };
  21750. /**
  21751. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21752. * @param key the unique key that identifies the data
  21753. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21754. * @return the associated data, can be null if the factory returned null.
  21755. */
  21756. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21757. if (!this._externalData) {
  21758. this._externalData = new BABYLON.StringDictionary();
  21759. }
  21760. return this._externalData.getOrAddWithFactory(key, factory);
  21761. };
  21762. /**
  21763. * Remove an externaly attached data from the Engine instance
  21764. * @param key the unique key that identifies the data
  21765. * @return true if the data was successfully removed, false if it doesn't exist
  21766. */
  21767. Scene.prototype.removeExternalData = function (key) {
  21768. return this._externalData.remove(key);
  21769. };
  21770. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21771. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21772. if (mesh.showSubMeshesBoundingBox) {
  21773. var boundingInfo = subMesh.getBoundingInfo();
  21774. if (boundingInfo !== null && boundingInfo !== undefined) {
  21775. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21776. }
  21777. }
  21778. var material = subMesh.getMaterial();
  21779. if (material !== null && material !== undefined) {
  21780. // Render targets
  21781. if (material.getRenderTargetTextures !== undefined) {
  21782. if (this._processedMaterials.indexOf(material) === -1) {
  21783. this._processedMaterials.push(material);
  21784. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21785. }
  21786. }
  21787. // Dispatch
  21788. this._activeIndices.addCount(subMesh.indexCount, false);
  21789. this._renderingManager.dispatch(subMesh, mesh, material);
  21790. }
  21791. }
  21792. };
  21793. Scene.prototype._isInIntermediateRendering = function () {
  21794. return this._intermediateRendering;
  21795. };
  21796. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  21797. this._activeMeshCandidateProvider = provider;
  21798. };
  21799. Scene.prototype.getActiveMeshCandidateProvider = function () {
  21800. return this._activeMeshCandidateProvider;
  21801. };
  21802. /**
  21803. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  21804. */
  21805. Scene.prototype.freezeActiveMeshes = function () {
  21806. this._evaluateActiveMeshes();
  21807. this._activeMeshesFrozen = true;
  21808. return this;
  21809. };
  21810. /**
  21811. * Use this function to restart evaluating active meshes on every frame
  21812. */
  21813. Scene.prototype.unfreezeActiveMeshes = function () {
  21814. this._activeMeshesFrozen = false;
  21815. return this;
  21816. };
  21817. Scene.prototype._evaluateActiveMeshes = function () {
  21818. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  21819. return;
  21820. }
  21821. if (!this.activeCamera) {
  21822. return;
  21823. }
  21824. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  21825. this.activeCamera._activeMeshes.reset();
  21826. this._activeMeshes.reset();
  21827. this._renderingManager.reset();
  21828. this._processedMaterials.reset();
  21829. this._activeParticleSystems.reset();
  21830. this._activeSkeletons.reset();
  21831. this._softwareSkinnedMeshes.reset();
  21832. if (this._boundingBoxRenderer) {
  21833. this._boundingBoxRenderer.reset();
  21834. }
  21835. // Meshes
  21836. var meshes;
  21837. var len;
  21838. var checkIsEnabled = true;
  21839. // Determine mesh candidates
  21840. if (this._activeMeshCandidateProvider !== undefined) {
  21841. // Use _activeMeshCandidateProvider
  21842. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  21843. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  21844. if (meshes !== undefined) {
  21845. len = meshes.length;
  21846. }
  21847. else {
  21848. len = 0;
  21849. }
  21850. }
  21851. else if (this._selectionOctree !== undefined) {
  21852. // Octree
  21853. var selection = this._selectionOctree.select(this._frustumPlanes);
  21854. meshes = selection.data;
  21855. len = selection.length;
  21856. }
  21857. else {
  21858. // Full scene traversal
  21859. len = this.meshes.length;
  21860. meshes = this.meshes;
  21861. }
  21862. // Check each mesh
  21863. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  21864. mesh = meshes[meshIndex];
  21865. if (mesh.isBlocked) {
  21866. continue;
  21867. }
  21868. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21869. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  21870. continue;
  21871. }
  21872. mesh.computeWorldMatrix();
  21873. // Intersections
  21874. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21875. this._meshesForIntersections.pushNoDuplicate(mesh);
  21876. }
  21877. // Switch to current LOD
  21878. meshLOD = mesh.getLOD(this.activeCamera);
  21879. if (meshLOD === undefined || meshLOD === null) {
  21880. continue;
  21881. }
  21882. mesh._preActivate();
  21883. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21884. this._activeMeshes.push(mesh);
  21885. this.activeCamera._activeMeshes.push(mesh);
  21886. mesh._activate(this._renderId);
  21887. if (meshLOD !== mesh) {
  21888. meshLOD._activate(this._renderId);
  21889. }
  21890. this._activeMesh(mesh, meshLOD);
  21891. }
  21892. }
  21893. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  21894. // Particle systems
  21895. if (this.particlesEnabled) {
  21896. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  21897. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21898. var particleSystem = this.particleSystems[particleIndex];
  21899. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  21900. continue;
  21901. }
  21902. var emitter = particleSystem.emitter;
  21903. if (!emitter.position || emitter.isEnabled()) {
  21904. this._activeParticleSystems.push(particleSystem);
  21905. particleSystem.animate();
  21906. this._renderingManager.dispatchParticles(particleSystem);
  21907. }
  21908. }
  21909. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  21910. }
  21911. };
  21912. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21913. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  21914. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21915. mesh.skeleton.prepare();
  21916. }
  21917. if (!mesh.computeBonesUsingShaders) {
  21918. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21919. }
  21920. }
  21921. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21922. var boundingInfo = sourceMesh.getBoundingInfo();
  21923. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21924. }
  21925. if (mesh !== undefined && mesh !== null
  21926. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  21927. // Submeshes Octrees
  21928. var len;
  21929. var subMeshes;
  21930. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  21931. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21932. len = intersections.length;
  21933. subMeshes = intersections.data;
  21934. }
  21935. else {
  21936. subMeshes = mesh.subMeshes;
  21937. len = subMeshes.length;
  21938. }
  21939. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  21940. subMesh = subMeshes[subIndex];
  21941. this._evaluateSubMesh(subMesh, mesh);
  21942. }
  21943. }
  21944. };
  21945. Scene.prototype.updateTransformMatrix = function (force) {
  21946. if (!this.activeCamera) {
  21947. return;
  21948. }
  21949. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21950. };
  21951. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  21952. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  21953. };
  21954. Scene.prototype._renderForCamera = function (camera) {
  21955. if (camera && camera._skipRendering) {
  21956. return;
  21957. }
  21958. var engine = this._engine;
  21959. this.activeCamera = camera;
  21960. if (!this.activeCamera)
  21961. throw new Error("Active camera not set");
  21962. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21963. // Viewport
  21964. engine.setViewport(this.activeCamera.viewport);
  21965. // Camera
  21966. this.resetCachedMaterial();
  21967. this._renderId++;
  21968. this.activeCamera.update();
  21969. this.updateTransformMatrix();
  21970. if (camera._alternateCamera) {
  21971. this.updateAlternateTransformMatrix(camera._alternateCamera);
  21972. this._alternateRendering = true;
  21973. }
  21974. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21975. // Meshes
  21976. this._evaluateActiveMeshes();
  21977. // Software skinning
  21978. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21979. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21980. mesh.applySkeleton(mesh.skeleton);
  21981. }
  21982. // Render targets
  21983. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  21984. var needsRestoreFrameBuffer = false;
  21985. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  21986. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  21987. }
  21988. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  21989. this._intermediateRendering = true;
  21990. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21991. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  21992. var renderTarget = this._renderTargets.data[renderIndex];
  21993. if (renderTarget._shouldRender()) {
  21994. this._renderId++;
  21995. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  21996. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  21997. }
  21998. }
  21999. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22000. this._intermediateRendering = false;
  22001. this._renderId++;
  22002. needsRestoreFrameBuffer = true; // Restore back buffer
  22003. }
  22004. // Render HighlightLayer Texture
  22005. var stencilState = this._engine.getStencilBuffer();
  22006. var renderhighlights = false;
  22007. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22008. this._intermediateRendering = true;
  22009. for (var i = 0; i < this.highlightLayers.length; i++) {
  22010. var highlightLayer = this.highlightLayers[i];
  22011. if (highlightLayer.shouldRender() &&
  22012. (!highlightLayer.camera ||
  22013. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22014. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22015. renderhighlights = true;
  22016. var renderTarget = highlightLayer._mainTexture;
  22017. if (renderTarget._shouldRender()) {
  22018. this._renderId++;
  22019. renderTarget.render(false, false);
  22020. needsRestoreFrameBuffer = true;
  22021. }
  22022. }
  22023. }
  22024. this._intermediateRendering = false;
  22025. this._renderId++;
  22026. }
  22027. if (needsRestoreFrameBuffer) {
  22028. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22029. }
  22030. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22031. // Prepare Frame
  22032. this.postProcessManager._prepareFrame();
  22033. // Backgrounds
  22034. var layerIndex;
  22035. var layer;
  22036. if (this.layers.length) {
  22037. engine.setDepthBuffer(false);
  22038. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22039. layer = this.layers[layerIndex];
  22040. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22041. layer.render();
  22042. }
  22043. }
  22044. engine.setDepthBuffer(true);
  22045. }
  22046. // Activate HighlightLayer stencil
  22047. if (renderhighlights) {
  22048. this._engine.setStencilBuffer(true);
  22049. }
  22050. // Render
  22051. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22052. this._renderingManager.render(null, null, true, true);
  22053. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22054. // Restore HighlightLayer stencil
  22055. if (renderhighlights) {
  22056. this._engine.setStencilBuffer(stencilState);
  22057. }
  22058. // Bounding boxes
  22059. if (this._boundingBoxRenderer) {
  22060. this._boundingBoxRenderer.render();
  22061. }
  22062. // Lens flares
  22063. if (this.lensFlaresEnabled) {
  22064. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22065. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22066. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22067. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22068. lensFlareSystem.render();
  22069. }
  22070. }
  22071. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22072. }
  22073. // Foregrounds
  22074. if (this.layers.length) {
  22075. engine.setDepthBuffer(false);
  22076. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22077. layer = this.layers[layerIndex];
  22078. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22079. layer.render();
  22080. }
  22081. }
  22082. engine.setDepthBuffer(true);
  22083. }
  22084. // Highlight Layer
  22085. if (renderhighlights) {
  22086. engine.setDepthBuffer(false);
  22087. for (var i = 0; i < this.highlightLayers.length; i++) {
  22088. if (this.highlightLayers[i].shouldRender()) {
  22089. this.highlightLayers[i].render();
  22090. }
  22091. }
  22092. engine.setDepthBuffer(true);
  22093. }
  22094. // Finalize frame
  22095. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22096. // Reset some special arrays
  22097. this._renderTargets.reset();
  22098. this._alternateRendering = false;
  22099. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22100. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22101. };
  22102. Scene.prototype._processSubCameras = function (camera) {
  22103. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22104. this._renderForCamera(camera);
  22105. return;
  22106. }
  22107. // Update camera
  22108. if (this.activeCamera) {
  22109. this.activeCamera.update();
  22110. }
  22111. // rig cameras
  22112. for (var index = 0; index < camera._rigCameras.length; index++) {
  22113. this._renderForCamera(camera._rigCameras[index]);
  22114. }
  22115. this.activeCamera = camera;
  22116. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22117. };
  22118. Scene.prototype._checkIntersections = function () {
  22119. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22120. var sourceMesh = this._meshesForIntersections.data[index];
  22121. if (!sourceMesh.actionManager) {
  22122. continue;
  22123. }
  22124. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22125. var action = sourceMesh.actionManager.actions[actionIndex];
  22126. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22127. var parameters = action.getTriggerParameter();
  22128. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22129. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22130. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22131. if (areIntersecting && currentIntersectionInProgress === -1) {
  22132. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22133. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22134. sourceMesh._intersectionsInProgress.push(otherMesh);
  22135. }
  22136. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22137. sourceMesh._intersectionsInProgress.push(otherMesh);
  22138. }
  22139. }
  22140. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22141. //They intersected, and now they don't.
  22142. //is this trigger an exit trigger? execute an event.
  22143. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22144. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22145. }
  22146. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22147. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22148. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22149. }
  22150. }
  22151. }
  22152. }
  22153. }
  22154. };
  22155. Scene.prototype.render = function () {
  22156. if (this.isDisposed) {
  22157. return;
  22158. }
  22159. this._activeParticles.fetchNewFrame();
  22160. this._totalVertices.fetchNewFrame();
  22161. this._activeIndices.fetchNewFrame();
  22162. this._activeBones.fetchNewFrame();
  22163. this._meshesForIntersections.reset();
  22164. this.resetCachedMaterial();
  22165. this.onBeforeAnimationsObservable.notifyObservers(this);
  22166. // Actions
  22167. if (this.actionManager) {
  22168. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22169. }
  22170. //Simplification Queue
  22171. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22172. this.simplificationQueue.executeNext();
  22173. }
  22174. if (this._engine.isDeterministicLockStep()) {
  22175. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22176. var defaultFPS = (60.0 / 1000.0);
  22177. var defaultFrameTime = 1000 / 60; // frame time in MS
  22178. if (this._physicsEngine) {
  22179. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22180. }
  22181. var stepsTaken = 0;
  22182. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22183. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22184. internalSteps = Math.min(internalSteps, maxSubSteps);
  22185. do {
  22186. this.onBeforeStepObservable.notifyObservers(this);
  22187. // Animations
  22188. this._animationRatio = defaultFrameTime * defaultFPS;
  22189. this._animate();
  22190. this.onAfterAnimationsObservable.notifyObservers(this);
  22191. // Physics
  22192. if (this._physicsEngine) {
  22193. this.onBeforePhysicsObservable.notifyObservers(this);
  22194. this._physicsEngine._step(defaultFrameTime / 1000);
  22195. this.onAfterPhysicsObservable.notifyObservers(this);
  22196. }
  22197. this.onAfterStepObservable.notifyObservers(this);
  22198. this._currentStepId++;
  22199. stepsTaken++;
  22200. deltaTime -= defaultFrameTime;
  22201. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22202. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22203. }
  22204. else {
  22205. // Animations
  22206. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22207. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22208. this._animate();
  22209. this.onAfterAnimationsObservable.notifyObservers(this);
  22210. // Physics
  22211. if (this._physicsEngine) {
  22212. this.onBeforePhysicsObservable.notifyObservers(this);
  22213. this._physicsEngine._step(deltaTime / 1000.0);
  22214. this.onAfterPhysicsObservable.notifyObservers(this);
  22215. }
  22216. }
  22217. // update gamepad manager
  22218. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22219. this._gamepadManager._checkGamepadsStatus();
  22220. }
  22221. // Before render
  22222. this.onBeforeRenderObservable.notifyObservers(this);
  22223. // Customs render targets
  22224. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22225. var engine = this.getEngine();
  22226. var currentActiveCamera = this.activeCamera;
  22227. if (this.renderTargetsEnabled) {
  22228. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22229. this._intermediateRendering = true;
  22230. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22231. var renderTarget = this.customRenderTargets[customIndex];
  22232. if (renderTarget._shouldRender()) {
  22233. this._renderId++;
  22234. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22235. if (!this.activeCamera)
  22236. throw new Error("Active camera not set");
  22237. // Viewport
  22238. engine.setViewport(this.activeCamera.viewport);
  22239. // Camera
  22240. this.updateTransformMatrix();
  22241. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22242. }
  22243. }
  22244. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22245. this._intermediateRendering = false;
  22246. this._renderId++;
  22247. }
  22248. // Restore back buffer
  22249. if (this.customRenderTargets.length > 0) {
  22250. engine.restoreDefaultFramebuffer();
  22251. }
  22252. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22253. this.activeCamera = currentActiveCamera;
  22254. // Procedural textures
  22255. if (this.proceduralTexturesEnabled) {
  22256. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22257. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22258. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22259. if (proceduralTexture._shouldRender()) {
  22260. proceduralTexture.render();
  22261. }
  22262. }
  22263. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22264. }
  22265. // Clear
  22266. if (this.autoClearDepthAndStencil || this.autoClear) {
  22267. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22268. }
  22269. // Shadows
  22270. if (this.shadowsEnabled) {
  22271. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22272. var light = this.lights[lightIndex];
  22273. var shadowGenerator = light.getShadowGenerator();
  22274. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22275. var shadowMap = (shadowGenerator.getShadowMap());
  22276. if (this.textures.indexOf(shadowMap) !== -1) {
  22277. this._renderTargets.push(shadowMap);
  22278. }
  22279. }
  22280. }
  22281. }
  22282. // Depth renderer
  22283. if (this._depthRenderer) {
  22284. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22285. }
  22286. // Geometry renderer
  22287. if (this._geometryBufferRenderer) {
  22288. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22289. }
  22290. // RenderPipeline
  22291. if (this._postProcessRenderPipelineManager) {
  22292. this._postProcessRenderPipelineManager.update();
  22293. }
  22294. // Multi-cameras?
  22295. if (this.activeCameras.length > 0) {
  22296. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22297. if (cameraIndex > 0) {
  22298. this._engine.clear(null, false, true, true);
  22299. }
  22300. this._processSubCameras(this.activeCameras[cameraIndex]);
  22301. }
  22302. }
  22303. else {
  22304. if (!this.activeCamera) {
  22305. throw new Error("No camera defined");
  22306. }
  22307. this._processSubCameras(this.activeCamera);
  22308. }
  22309. // Intersection checks
  22310. this._checkIntersections();
  22311. // Update the audio listener attached to the camera
  22312. if (BABYLON.AudioEngine) {
  22313. this._updateAudioParameters();
  22314. }
  22315. // After render
  22316. if (this.afterRender) {
  22317. this.afterRender();
  22318. }
  22319. this.onAfterRenderObservable.notifyObservers(this);
  22320. // Cleaning
  22321. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22322. var data = this._toBeDisposed.data[index];
  22323. if (data) {
  22324. data.dispose();
  22325. }
  22326. this._toBeDisposed[index] = null;
  22327. }
  22328. this._toBeDisposed.reset();
  22329. if (this.dumpNextRenderTargets) {
  22330. this.dumpNextRenderTargets = false;
  22331. }
  22332. this._activeBones.addCount(0, true);
  22333. this._activeIndices.addCount(0, true);
  22334. this._activeParticles.addCount(0, true);
  22335. };
  22336. Scene.prototype._updateAudioParameters = function () {
  22337. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22338. return;
  22339. }
  22340. var listeningCamera;
  22341. var audioEngine = BABYLON.Engine.audioEngine;
  22342. if (this.activeCameras.length > 0) {
  22343. listeningCamera = this.activeCameras[0];
  22344. }
  22345. else {
  22346. listeningCamera = this.activeCamera;
  22347. }
  22348. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22349. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22350. // for VR cameras
  22351. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22352. listeningCamera = listeningCamera.rigCameras[0];
  22353. }
  22354. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22355. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22356. cameraDirection.normalize();
  22357. // To avoid some errors on GearVR
  22358. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22359. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22360. }
  22361. var i;
  22362. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22363. var sound = this.mainSoundTrack.soundCollection[i];
  22364. if (sound.useCustomAttenuation) {
  22365. sound.updateDistanceFromListener();
  22366. }
  22367. }
  22368. for (i = 0; i < this.soundTracks.length; i++) {
  22369. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22370. sound = this.soundTracks[i].soundCollection[j];
  22371. if (sound.useCustomAttenuation) {
  22372. sound.updateDistanceFromListener();
  22373. }
  22374. }
  22375. }
  22376. }
  22377. };
  22378. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22379. // Audio
  22380. get: function () {
  22381. return this._audioEnabled;
  22382. },
  22383. set: function (value) {
  22384. this._audioEnabled = value;
  22385. if (BABYLON.AudioEngine) {
  22386. if (this._audioEnabled) {
  22387. this._enableAudio();
  22388. }
  22389. else {
  22390. this._disableAudio();
  22391. }
  22392. }
  22393. },
  22394. enumerable: true,
  22395. configurable: true
  22396. });
  22397. Scene.prototype._disableAudio = function () {
  22398. var i;
  22399. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22400. this.mainSoundTrack.soundCollection[i].pause();
  22401. }
  22402. for (i = 0; i < this.soundTracks.length; i++) {
  22403. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22404. this.soundTracks[i].soundCollection[j].pause();
  22405. }
  22406. }
  22407. };
  22408. Scene.prototype._enableAudio = function () {
  22409. var i;
  22410. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22411. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22412. this.mainSoundTrack.soundCollection[i].play();
  22413. }
  22414. }
  22415. for (i = 0; i < this.soundTracks.length; i++) {
  22416. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22417. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22418. this.soundTracks[i].soundCollection[j].play();
  22419. }
  22420. }
  22421. }
  22422. };
  22423. Object.defineProperty(Scene.prototype, "headphone", {
  22424. get: function () {
  22425. return this._headphone;
  22426. },
  22427. set: function (value) {
  22428. this._headphone = value;
  22429. if (BABYLON.AudioEngine) {
  22430. if (this._headphone) {
  22431. this._switchAudioModeForHeadphones();
  22432. }
  22433. else {
  22434. this._switchAudioModeForNormalSpeakers();
  22435. }
  22436. }
  22437. },
  22438. enumerable: true,
  22439. configurable: true
  22440. });
  22441. Scene.prototype._switchAudioModeForHeadphones = function () {
  22442. this.mainSoundTrack.switchPanningModelToHRTF();
  22443. for (var i = 0; i < this.soundTracks.length; i++) {
  22444. this.soundTracks[i].switchPanningModelToHRTF();
  22445. }
  22446. };
  22447. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22448. this.mainSoundTrack.switchPanningModelToEqualPower();
  22449. for (var i = 0; i < this.soundTracks.length; i++) {
  22450. this.soundTracks[i].switchPanningModelToEqualPower();
  22451. }
  22452. };
  22453. Scene.prototype.enableDepthRenderer = function () {
  22454. if (this._depthRenderer) {
  22455. return this._depthRenderer;
  22456. }
  22457. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22458. return this._depthRenderer;
  22459. };
  22460. Scene.prototype.disableDepthRenderer = function () {
  22461. if (!this._depthRenderer) {
  22462. return;
  22463. }
  22464. this._depthRenderer.dispose();
  22465. this._depthRenderer = null;
  22466. };
  22467. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  22468. if (ratio === void 0) { ratio = 1; }
  22469. if (this._geometryBufferRenderer) {
  22470. return this._geometryBufferRenderer;
  22471. }
  22472. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  22473. if (!this._geometryBufferRenderer.isSupported) {
  22474. this._geometryBufferRenderer = null;
  22475. }
  22476. return this._geometryBufferRenderer;
  22477. };
  22478. Scene.prototype.disableGeometryBufferRenderer = function () {
  22479. if (!this._geometryBufferRenderer) {
  22480. return;
  22481. }
  22482. this._geometryBufferRenderer.dispose();
  22483. this._geometryBufferRenderer = null;
  22484. };
  22485. Scene.prototype.freezeMaterials = function () {
  22486. for (var i = 0; i < this.materials.length; i++) {
  22487. this.materials[i].freeze();
  22488. }
  22489. };
  22490. Scene.prototype.unfreezeMaterials = function () {
  22491. for (var i = 0; i < this.materials.length; i++) {
  22492. this.materials[i].unfreeze();
  22493. }
  22494. };
  22495. Scene.prototype.dispose = function () {
  22496. this.beforeRender = null;
  22497. this.afterRender = null;
  22498. this.skeletons = [];
  22499. this.morphTargetManagers = [];
  22500. this.importedMeshesFiles = new Array();
  22501. this.stopAllAnimations();
  22502. this.resetCachedMaterial();
  22503. if (this._depthRenderer) {
  22504. this._depthRenderer.dispose();
  22505. }
  22506. if (this._gamepadManager) {
  22507. this._gamepadManager.dispose();
  22508. this._gamepadManager = null;
  22509. }
  22510. // Smart arrays
  22511. if (this.activeCamera) {
  22512. this.activeCamera._activeMeshes.dispose();
  22513. this.activeCamera = null;
  22514. }
  22515. this._activeMeshes.dispose();
  22516. this._renderingManager.dispose();
  22517. this._processedMaterials.dispose();
  22518. this._activeParticleSystems.dispose();
  22519. this._activeSkeletons.dispose();
  22520. this._softwareSkinnedMeshes.dispose();
  22521. this._renderTargets.dispose();
  22522. if (this._boundingBoxRenderer) {
  22523. this._boundingBoxRenderer.dispose();
  22524. }
  22525. this._meshesForIntersections.dispose();
  22526. this._toBeDisposed.dispose();
  22527. // Abort active requests
  22528. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  22529. var request = _a[_i];
  22530. request.abort();
  22531. }
  22532. // Debug layer
  22533. if (this._debugLayer) {
  22534. this._debugLayer.hide();
  22535. }
  22536. // Events
  22537. this.onDisposeObservable.notifyObservers(this);
  22538. this.onDisposeObservable.clear();
  22539. this.onBeforeRenderObservable.clear();
  22540. this.onAfterRenderObservable.clear();
  22541. this.OnBeforeRenderTargetsRenderObservable.clear();
  22542. this.OnAfterRenderTargetsRenderObservable.clear();
  22543. this.onAfterStepObservable.clear();
  22544. this.onBeforeStepObservable.clear();
  22545. this.onBeforeActiveMeshesEvaluationObservable.clear();
  22546. this.onAfterActiveMeshesEvaluationObservable.clear();
  22547. this.onBeforeParticlesRenderingObservable.clear();
  22548. this.onAfterParticlesRenderingObservable.clear();
  22549. this.onBeforeSpritesRenderingObservable.clear();
  22550. this.onAfterSpritesRenderingObservable.clear();
  22551. this.onBeforeDrawPhaseObservable.clear();
  22552. this.onAfterDrawPhaseObservable.clear();
  22553. this.onBeforePhysicsObservable.clear();
  22554. this.onAfterPhysicsObservable.clear();
  22555. this.onBeforeAnimationsObservable.clear();
  22556. this.onAfterAnimationsObservable.clear();
  22557. this.onDataLoadedObservable.clear();
  22558. this.detachControl();
  22559. // Release sounds & sounds tracks
  22560. if (BABYLON.AudioEngine) {
  22561. this.disposeSounds();
  22562. }
  22563. // VR Helper
  22564. if (this.VRHelper) {
  22565. this.VRHelper.dispose();
  22566. }
  22567. // Detach cameras
  22568. var canvas = this._engine.getRenderingCanvas();
  22569. if (canvas) {
  22570. var index;
  22571. for (index = 0; index < this.cameras.length; index++) {
  22572. this.cameras[index].detachControl(canvas);
  22573. }
  22574. }
  22575. // Release animation groups
  22576. while (this.animationGroups.length) {
  22577. this.animationGroups[0].dispose();
  22578. }
  22579. // Release lights
  22580. while (this.lights.length) {
  22581. this.lights[0].dispose();
  22582. }
  22583. // Release meshes
  22584. while (this.meshes.length) {
  22585. this.meshes[0].dispose(true);
  22586. }
  22587. while (this.transformNodes.length) {
  22588. this.removeTransformNode(this.transformNodes[0]);
  22589. }
  22590. // Release cameras
  22591. while (this.cameras.length) {
  22592. this.cameras[0].dispose();
  22593. }
  22594. // Release materials
  22595. if (this.defaultMaterial) {
  22596. this.defaultMaterial.dispose();
  22597. }
  22598. while (this.multiMaterials.length) {
  22599. this.multiMaterials[0].dispose();
  22600. }
  22601. while (this.materials.length) {
  22602. this.materials[0].dispose();
  22603. }
  22604. // Release particles
  22605. while (this.particleSystems.length) {
  22606. this.particleSystems[0].dispose();
  22607. }
  22608. // Release sprites
  22609. while (this.spriteManagers.length) {
  22610. this.spriteManagers[0].dispose();
  22611. }
  22612. // Release postProcesses
  22613. while (this.postProcesses.length) {
  22614. this.postProcesses[0].dispose();
  22615. }
  22616. // Release layers
  22617. while (this.layers.length) {
  22618. this.layers[0].dispose();
  22619. }
  22620. while (this.highlightLayers.length) {
  22621. this.highlightLayers[0].dispose();
  22622. }
  22623. // Release textures
  22624. while (this.textures.length) {
  22625. this.textures[0].dispose();
  22626. }
  22627. // Release UBO
  22628. this._sceneUbo.dispose();
  22629. if (this._alternateSceneUbo) {
  22630. this._alternateSceneUbo.dispose();
  22631. }
  22632. // Post-processes
  22633. this.postProcessManager.dispose();
  22634. if (this._postProcessRenderPipelineManager) {
  22635. this._postProcessRenderPipelineManager.dispose();
  22636. }
  22637. // Physics
  22638. if (this._physicsEngine) {
  22639. this.disablePhysicsEngine();
  22640. }
  22641. // Remove from engine
  22642. index = this._engine.scenes.indexOf(this);
  22643. if (index > -1) {
  22644. this._engine.scenes.splice(index, 1);
  22645. }
  22646. this._engine.wipeCaches(true);
  22647. this._isDisposed = true;
  22648. };
  22649. Object.defineProperty(Scene.prototype, "isDisposed", {
  22650. get: function () {
  22651. return this._isDisposed;
  22652. },
  22653. enumerable: true,
  22654. configurable: true
  22655. });
  22656. // Release sounds & sounds tracks
  22657. Scene.prototype.disposeSounds = function () {
  22658. if (!this._mainSoundTrack) {
  22659. return;
  22660. }
  22661. this.mainSoundTrack.dispose();
  22662. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22663. this.soundTracks[scIndex].dispose();
  22664. }
  22665. };
  22666. // Octrees
  22667. Scene.prototype.getWorldExtends = function () {
  22668. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22669. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22670. for (var index = 0; index < this.meshes.length; index++) {
  22671. var mesh = this.meshes[index];
  22672. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  22673. continue;
  22674. }
  22675. mesh.computeWorldMatrix(true);
  22676. var boundingInfo = mesh.getBoundingInfo();
  22677. var minBox = boundingInfo.boundingBox.minimumWorld;
  22678. var maxBox = boundingInfo.boundingBox.maximumWorld;
  22679. BABYLON.Tools.CheckExtends(minBox, min, max);
  22680. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22681. }
  22682. return {
  22683. min: min,
  22684. max: max
  22685. };
  22686. };
  22687. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22688. if (maxCapacity === void 0) { maxCapacity = 64; }
  22689. if (maxDepth === void 0) { maxDepth = 2; }
  22690. if (!this._selectionOctree) {
  22691. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  22692. }
  22693. var worldExtends = this.getWorldExtends();
  22694. // Update octree
  22695. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  22696. return this._selectionOctree;
  22697. };
  22698. // Picking
  22699. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  22700. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22701. var result = BABYLON.Ray.Zero();
  22702. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  22703. return result;
  22704. };
  22705. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  22706. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22707. var engine = this._engine;
  22708. if (!camera) {
  22709. if (!this.activeCamera)
  22710. throw new Error("Active camera not set");
  22711. camera = this.activeCamera;
  22712. }
  22713. var cameraViewport = camera.viewport;
  22714. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22715. // Moving coordinates to local viewport world
  22716. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22717. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22718. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  22719. return this;
  22720. };
  22721. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22722. var result = BABYLON.Ray.Zero();
  22723. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  22724. return result;
  22725. };
  22726. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  22727. if (!BABYLON.PickingInfo) {
  22728. return this;
  22729. }
  22730. var engine = this._engine;
  22731. if (!camera) {
  22732. if (!this.activeCamera)
  22733. throw new Error("Active camera not set");
  22734. camera = this.activeCamera;
  22735. }
  22736. var cameraViewport = camera.viewport;
  22737. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22738. var identity = BABYLON.Matrix.Identity();
  22739. // Moving coordinates to local viewport world
  22740. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22741. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22742. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22743. return this;
  22744. };
  22745. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22746. if (!BABYLON.PickingInfo) {
  22747. return null;
  22748. }
  22749. var pickingInfo = null;
  22750. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22751. var mesh = this.meshes[meshIndex];
  22752. if (predicate) {
  22753. if (!predicate(mesh)) {
  22754. continue;
  22755. }
  22756. }
  22757. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22758. continue;
  22759. }
  22760. var world = mesh.getWorldMatrix();
  22761. var ray = rayFunction(world);
  22762. var result = mesh.intersects(ray, fastCheck);
  22763. if (!result || !result.hit)
  22764. continue;
  22765. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22766. continue;
  22767. pickingInfo = result;
  22768. if (fastCheck) {
  22769. break;
  22770. }
  22771. }
  22772. return pickingInfo || new BABYLON.PickingInfo();
  22773. };
  22774. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22775. if (!BABYLON.PickingInfo) {
  22776. return null;
  22777. }
  22778. var pickingInfos = new Array();
  22779. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22780. var mesh = this.meshes[meshIndex];
  22781. if (predicate) {
  22782. if (!predicate(mesh)) {
  22783. continue;
  22784. }
  22785. }
  22786. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22787. continue;
  22788. }
  22789. var world = mesh.getWorldMatrix();
  22790. var ray = rayFunction(world);
  22791. var result = mesh.intersects(ray, false);
  22792. if (!result || !result.hit)
  22793. continue;
  22794. pickingInfos.push(result);
  22795. }
  22796. return pickingInfos;
  22797. };
  22798. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22799. if (!BABYLON.PickingInfo) {
  22800. return null;
  22801. }
  22802. var pickingInfo = null;
  22803. if (!camera) {
  22804. if (!this.activeCamera) {
  22805. return null;
  22806. }
  22807. camera = this.activeCamera;
  22808. }
  22809. if (this.spriteManagers.length > 0) {
  22810. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22811. var spriteManager = this.spriteManagers[spriteIndex];
  22812. if (!spriteManager.isPickable) {
  22813. continue;
  22814. }
  22815. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22816. if (!result || !result.hit)
  22817. continue;
  22818. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22819. continue;
  22820. pickingInfo = result;
  22821. if (fastCheck) {
  22822. break;
  22823. }
  22824. }
  22825. }
  22826. return pickingInfo || new BABYLON.PickingInfo();
  22827. };
  22828. /** Launch a ray to try to pick a mesh in the scene
  22829. * @param x position on screen
  22830. * @param y position on screen
  22831. * @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
  22832. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22833. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22834. */
  22835. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22836. var _this = this;
  22837. if (!BABYLON.PickingInfo) {
  22838. return null;
  22839. }
  22840. return this._internalPick(function (world) {
  22841. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  22842. return _this._tempPickingRay;
  22843. }, predicate, fastCheck);
  22844. };
  22845. /** Launch a ray to try to pick a sprite in the scene
  22846. * @param x position on screen
  22847. * @param y position on screen
  22848. * @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
  22849. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22850. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22851. */
  22852. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22853. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  22854. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  22855. };
  22856. /** Use the given ray to pick a mesh in the scene
  22857. * @param ray The ray to use to pick meshes
  22858. * @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
  22859. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22860. */
  22861. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22862. var _this = this;
  22863. return this._internalPick(function (world) {
  22864. if (!_this._pickWithRayInverseMatrix) {
  22865. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22866. }
  22867. world.invertToRef(_this._pickWithRayInverseMatrix);
  22868. if (!_this._cachedRayForTransform) {
  22869. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22870. }
  22871. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22872. return _this._cachedRayForTransform;
  22873. }, predicate, fastCheck);
  22874. };
  22875. /**
  22876. * Launch a ray to try to pick a mesh in the scene
  22877. * @param x X position on screen
  22878. * @param y Y position on screen
  22879. * @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
  22880. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22881. */
  22882. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22883. var _this = this;
  22884. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  22885. };
  22886. /**
  22887. * Launch a ray to try to pick a mesh in the scene
  22888. * @param ray Ray to use
  22889. * @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
  22890. */
  22891. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22892. var _this = this;
  22893. return this._internalMultiPick(function (world) {
  22894. if (!_this._pickWithRayInverseMatrix) {
  22895. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22896. }
  22897. world.invertToRef(_this._pickWithRayInverseMatrix);
  22898. if (!_this._cachedRayForTransform) {
  22899. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22900. }
  22901. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22902. return _this._cachedRayForTransform;
  22903. }, predicate);
  22904. };
  22905. Scene.prototype.setPointerOverMesh = function (mesh) {
  22906. if (this._pointerOverMesh === mesh) {
  22907. return;
  22908. }
  22909. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22910. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22911. }
  22912. this._pointerOverMesh = mesh;
  22913. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22914. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22915. }
  22916. };
  22917. Scene.prototype.getPointerOverMesh = function () {
  22918. return this._pointerOverMesh;
  22919. };
  22920. Scene.prototype.setPointerOverSprite = function (sprite) {
  22921. if (this._pointerOverSprite === sprite) {
  22922. return;
  22923. }
  22924. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22925. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22926. }
  22927. this._pointerOverSprite = sprite;
  22928. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22929. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22930. }
  22931. };
  22932. Scene.prototype.getPointerOverSprite = function () {
  22933. return this._pointerOverSprite;
  22934. };
  22935. // Physics
  22936. Scene.prototype.getPhysicsEngine = function () {
  22937. return this._physicsEngine;
  22938. };
  22939. /**
  22940. * Enables physics to the current scene
  22941. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22942. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22943. * @return {boolean} was the physics engine initialized
  22944. */
  22945. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22946. if (gravity === void 0) { gravity = null; }
  22947. if (this._physicsEngine) {
  22948. return true;
  22949. }
  22950. try {
  22951. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22952. return true;
  22953. }
  22954. catch (e) {
  22955. BABYLON.Tools.Error(e.message);
  22956. return false;
  22957. }
  22958. };
  22959. Scene.prototype.disablePhysicsEngine = function () {
  22960. if (!this._physicsEngine) {
  22961. return;
  22962. }
  22963. this._physicsEngine.dispose();
  22964. this._physicsEngine = null;
  22965. };
  22966. Scene.prototype.isPhysicsEnabled = function () {
  22967. return this._physicsEngine !== undefined;
  22968. };
  22969. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22970. var mesh = compound.parts[0].mesh;
  22971. if (mesh.physicsImpostor) {
  22972. mesh.physicsImpostor.dispose();
  22973. mesh.physicsImpostor = null;
  22974. }
  22975. };
  22976. // Misc.
  22977. Scene.prototype._rebuildGeometries = function () {
  22978. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  22979. var geometry = _a[_i];
  22980. geometry._rebuild();
  22981. }
  22982. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  22983. var mesh = _c[_b];
  22984. mesh._rebuild();
  22985. }
  22986. if (this.postProcessManager) {
  22987. this.postProcessManager._rebuild();
  22988. }
  22989. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  22990. var layer = _e[_d];
  22991. layer._rebuild();
  22992. }
  22993. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  22994. var highlightLayer = _g[_f];
  22995. highlightLayer._rebuild();
  22996. }
  22997. if (this._boundingBoxRenderer) {
  22998. this._boundingBoxRenderer._rebuild();
  22999. }
  23000. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  23001. var system = _j[_h];
  23002. system.rebuild();
  23003. }
  23004. if (this._postProcessRenderPipelineManager) {
  23005. this._postProcessRenderPipelineManager._rebuild();
  23006. }
  23007. };
  23008. Scene.prototype._rebuildTextures = function () {
  23009. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  23010. var texture = _a[_i];
  23011. texture._rebuild();
  23012. }
  23013. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23014. };
  23015. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23016. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23017. if (replace === void 0) { replace = false; }
  23018. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23019. // Dispose existing camera or light in replace mode.
  23020. if (replace) {
  23021. if (this.activeCamera) {
  23022. this.activeCamera.dispose();
  23023. this.activeCamera = null;
  23024. }
  23025. if (this.lights) {
  23026. for (var i = 0; i < this.lights.length; i++) {
  23027. this.lights[i].dispose();
  23028. }
  23029. }
  23030. }
  23031. // Light
  23032. if (this.lights.length === 0) {
  23033. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23034. }
  23035. // Camera
  23036. if (!this.activeCamera) {
  23037. var worldExtends = this.getWorldExtends();
  23038. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23039. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23040. var camera;
  23041. var radius = worldSize.length() * 1.5;
  23042. if (createArcRotateCamera) {
  23043. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23044. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23045. arcRotateCamera.wheelPrecision = 100 / radius;
  23046. camera = arcRotateCamera;
  23047. }
  23048. else {
  23049. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23050. freeCamera.setTarget(worldCenter);
  23051. camera = freeCamera;
  23052. }
  23053. camera.minZ = radius * 0.01;
  23054. camera.maxZ = radius * 1000;
  23055. camera.speed = radius * 0.2;
  23056. this.activeCamera = camera;
  23057. var canvas = this.getEngine().getRenderingCanvas();
  23058. if (attachCameraControls && canvas) {
  23059. camera.attachControl(canvas);
  23060. }
  23061. }
  23062. };
  23063. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23064. if (pbr === void 0) { pbr = false; }
  23065. if (scale === void 0) { scale = 1000; }
  23066. if (blur === void 0) { blur = 0; }
  23067. if (environmentTexture) {
  23068. this.environmentTexture = environmentTexture;
  23069. }
  23070. if (!this.environmentTexture) {
  23071. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23072. return null;
  23073. }
  23074. // Skybox
  23075. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23076. if (pbr) {
  23077. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23078. hdrSkyboxMaterial.backFaceCulling = false;
  23079. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23080. if (hdrSkyboxMaterial.reflectionTexture) {
  23081. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23082. }
  23083. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23084. hdrSkyboxMaterial.disableLighting = true;
  23085. hdrSkyboxMaterial.twoSidedLighting = true;
  23086. hdrSkybox.infiniteDistance = true;
  23087. hdrSkybox.material = hdrSkyboxMaterial;
  23088. }
  23089. else {
  23090. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23091. skyboxMaterial.backFaceCulling = false;
  23092. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23093. if (skyboxMaterial.reflectionTexture) {
  23094. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23095. }
  23096. skyboxMaterial.disableLighting = true;
  23097. hdrSkybox.infiniteDistance = true;
  23098. hdrSkybox.material = skyboxMaterial;
  23099. }
  23100. return hdrSkybox;
  23101. };
  23102. Scene.prototype.createDefaultEnvironment = function (options) {
  23103. if (BABYLON.EnvironmentHelper) {
  23104. return new BABYLON.EnvironmentHelper(options, this);
  23105. }
  23106. return null;
  23107. };
  23108. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23109. if (webVROptions === void 0) { webVROptions = {}; }
  23110. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23111. };
  23112. // Tags
  23113. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23114. if (tagsQuery === undefined) {
  23115. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23116. return list;
  23117. }
  23118. var listByTags = [];
  23119. forEach = forEach || (function (item) { return; });
  23120. for (var i in list) {
  23121. var item = list[i];
  23122. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23123. listByTags.push(item);
  23124. forEach(item);
  23125. }
  23126. }
  23127. return listByTags;
  23128. };
  23129. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23130. return this._getByTags(this.meshes, tagsQuery, forEach);
  23131. };
  23132. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23133. return this._getByTags(this.cameras, tagsQuery, forEach);
  23134. };
  23135. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23136. return this._getByTags(this.lights, tagsQuery, forEach);
  23137. };
  23138. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23139. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23140. };
  23141. /**
  23142. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23143. * This allowed control for front to back rendering or reversly depending of the special needs.
  23144. *
  23145. * @param renderingGroupId The rendering group id corresponding to its index
  23146. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23147. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23148. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23149. */
  23150. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23151. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23152. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23153. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23154. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23155. };
  23156. /**
  23157. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23158. *
  23159. * @param renderingGroupId The rendering group id corresponding to its index
  23160. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23161. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23162. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23163. */
  23164. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23165. if (depth === void 0) { depth = true; }
  23166. if (stencil === void 0) { stencil = true; }
  23167. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23168. };
  23169. /**
  23170. * Will flag all materials as dirty to trigger new shader compilation
  23171. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23172. */
  23173. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23174. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23175. var material = _a[_i];
  23176. if (predicate && !predicate(material)) {
  23177. continue;
  23178. }
  23179. material.markAsDirty(flag);
  23180. }
  23181. };
  23182. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23183. var _this = this;
  23184. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23185. this._activeRequests.push(request);
  23186. request.onCompleteObservable.add(function (request) {
  23187. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23188. });
  23189. return request;
  23190. };
  23191. // Statics
  23192. Scene._FOGMODE_NONE = 0;
  23193. Scene._FOGMODE_EXP = 1;
  23194. Scene._FOGMODE_EXP2 = 2;
  23195. Scene._FOGMODE_LINEAR = 3;
  23196. Scene._uniqueIdCounter = 0;
  23197. Scene.MinDeltaTime = 1.0;
  23198. Scene.MaxDeltaTime = 1000.0;
  23199. /** The distance in pixel that you have to move to prevent some events */
  23200. Scene.DragMovementThreshold = 10; // in pixels
  23201. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23202. Scene.LongPressDelay = 500; // in milliseconds
  23203. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23204. Scene.DoubleClickDelay = 300; // in milliseconds
  23205. /** If you need to check double click without raising a single click at first click, enable this flag */
  23206. Scene.ExclusiveDoubleClickMode = false;
  23207. return Scene;
  23208. }());
  23209. BABYLON.Scene = Scene;
  23210. })(BABYLON || (BABYLON = {}));
  23211. //# sourceMappingURL=babylon.scene.js.map
  23212. var BABYLON;
  23213. (function (BABYLON) {
  23214. var AssetContainer = /** @class */ (function () {
  23215. function AssetContainer(scene) {
  23216. // Objects
  23217. this.cameras = new Array();
  23218. this.lights = new Array();
  23219. this.meshes = new Array();
  23220. this.skeletons = new Array();
  23221. this.particleSystems = new Array();
  23222. this.animations = new Array();
  23223. this.multiMaterials = new Array();
  23224. this.materials = new Array();
  23225. this.morphTargetManagers = new Array();
  23226. this.geometries = new Array();
  23227. this.transformNodes = new Array();
  23228. this.lensFlareSystems = new Array();
  23229. this.shadowGenerators = new Array();
  23230. this.actionManagers = new Array();
  23231. this.sounds = new Array();
  23232. this.scene = scene;
  23233. }
  23234. AssetContainer.prototype.addAllToScene = function () {
  23235. var _this = this;
  23236. this.cameras.forEach(function (o) {
  23237. _this.scene.addCamera(o);
  23238. });
  23239. this.lights.forEach(function (o) {
  23240. _this.scene.addLight(o);
  23241. });
  23242. this.meshes.forEach(function (o) {
  23243. _this.scene.addMesh(o);
  23244. });
  23245. this.skeletons.forEach(function (o) {
  23246. _this.scene.addSkeleton(o);
  23247. });
  23248. this.particleSystems.forEach(function (o) {
  23249. _this.scene.addParticleSystem(o);
  23250. });
  23251. this.animations.forEach(function (o) {
  23252. _this.scene.addAnimation(o);
  23253. });
  23254. this.multiMaterials.forEach(function (o) {
  23255. _this.scene.addMultiMaterial(o);
  23256. });
  23257. this.materials.forEach(function (o) {
  23258. _this.scene.addMaterial(o);
  23259. });
  23260. this.morphTargetManagers.forEach(function (o) {
  23261. _this.scene.addMorphTargetManager(o);
  23262. });
  23263. this.geometries.forEach(function (o) {
  23264. _this.scene.addGeometry(o);
  23265. });
  23266. this.transformNodes.forEach(function (o) {
  23267. _this.scene.addTransformNode(o);
  23268. });
  23269. this.lensFlareSystems.forEach(function (o) {
  23270. _this.scene.addLensFlareSystem(o);
  23271. });
  23272. this.actionManagers.forEach(function (o) {
  23273. _this.scene.addActionManager(o);
  23274. });
  23275. this.sounds.forEach(function (o) {
  23276. o.play();
  23277. o.autoplay = true;
  23278. _this.scene.mainSoundTrack.AddSound(o);
  23279. });
  23280. };
  23281. AssetContainer.prototype.removeAllFromScene = function () {
  23282. var _this = this;
  23283. this.cameras.forEach(function (o) {
  23284. _this.scene.removeCamera(o);
  23285. });
  23286. this.lights.forEach(function (o) {
  23287. _this.scene.removeLight(o);
  23288. });
  23289. this.meshes.forEach(function (o) {
  23290. _this.scene.removeMesh(o);
  23291. });
  23292. this.skeletons.forEach(function (o) {
  23293. _this.scene.removeSkeleton(o);
  23294. });
  23295. this.particleSystems.forEach(function (o) {
  23296. _this.scene.removeParticleSystem(o);
  23297. });
  23298. this.animations.forEach(function (o) {
  23299. _this.scene.removeAnimation(o);
  23300. });
  23301. this.multiMaterials.forEach(function (o) {
  23302. _this.scene.removeMultiMaterial(o);
  23303. });
  23304. this.materials.forEach(function (o) {
  23305. _this.scene.removeMaterial(o);
  23306. });
  23307. this.morphTargetManagers.forEach(function (o) {
  23308. _this.scene.removeMorphTargetManager(o);
  23309. });
  23310. this.geometries.forEach(function (o) {
  23311. _this.scene.removeGeometry(o);
  23312. });
  23313. this.transformNodes.forEach(function (o) {
  23314. _this.scene.removeTransformNode(o);
  23315. });
  23316. this.lensFlareSystems.forEach(function (o) {
  23317. _this.scene.removeLensFlareSystem(o);
  23318. });
  23319. this.actionManagers.forEach(function (o) {
  23320. _this.scene.removeActionManager(o);
  23321. });
  23322. this.sounds.forEach(function (o) {
  23323. o.stop();
  23324. o.autoplay = false;
  23325. _this.scene.mainSoundTrack.RemoveSound(o);
  23326. });
  23327. };
  23328. return AssetContainer;
  23329. }());
  23330. BABYLON.AssetContainer = AssetContainer;
  23331. })(BABYLON || (BABYLON = {}));
  23332. //# sourceMappingURL=babylon.assetContainer.js.map
  23333. var BABYLON;
  23334. (function (BABYLON) {
  23335. var Buffer = /** @class */ (function () {
  23336. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23337. if (instanced === void 0) { instanced = false; }
  23338. if (engine instanceof BABYLON.Mesh) {
  23339. this._engine = engine.getScene().getEngine();
  23340. }
  23341. else {
  23342. this._engine = engine;
  23343. }
  23344. this._updatable = updatable;
  23345. this._data = data;
  23346. this._strideSize = stride;
  23347. if (!postponeInternalCreation) {
  23348. this.create();
  23349. }
  23350. this._instanced = instanced;
  23351. this._instanceDivisor = instanced ? 1 : 0;
  23352. }
  23353. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23354. // a lot of these parameters are ignored as they are overriden by the buffer
  23355. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23356. };
  23357. // Properties
  23358. Buffer.prototype.isUpdatable = function () {
  23359. return this._updatable;
  23360. };
  23361. Buffer.prototype.getData = function () {
  23362. return this._data;
  23363. };
  23364. Buffer.prototype.getBuffer = function () {
  23365. return this._buffer;
  23366. };
  23367. Buffer.prototype.getStrideSize = function () {
  23368. return this._strideSize;
  23369. };
  23370. Buffer.prototype.getIsInstanced = function () {
  23371. return this._instanced;
  23372. };
  23373. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  23374. get: function () {
  23375. return this._instanceDivisor;
  23376. },
  23377. set: function (value) {
  23378. this._instanceDivisor = value;
  23379. if (value == 0) {
  23380. this._instanced = false;
  23381. }
  23382. else {
  23383. this._instanced = true;
  23384. }
  23385. },
  23386. enumerable: true,
  23387. configurable: true
  23388. });
  23389. // Methods
  23390. Buffer.prototype.create = function (data) {
  23391. if (data === void 0) { data = null; }
  23392. if (!data && this._buffer) {
  23393. return; // nothing to do
  23394. }
  23395. data = data || this._data;
  23396. if (!data) {
  23397. return;
  23398. }
  23399. if (!this._buffer) {
  23400. if (this._updatable) {
  23401. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23402. this._data = data;
  23403. }
  23404. else {
  23405. this._buffer = this._engine.createVertexBuffer(data);
  23406. }
  23407. }
  23408. else if (this._updatable) {
  23409. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23410. this._data = data;
  23411. }
  23412. };
  23413. Buffer.prototype._rebuild = function () {
  23414. this._buffer = null;
  23415. this.create(this._data);
  23416. };
  23417. Buffer.prototype.update = function (data) {
  23418. this.create(data);
  23419. };
  23420. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23421. if (!this._buffer) {
  23422. return;
  23423. }
  23424. if (this._updatable) {
  23425. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23426. this._data = null;
  23427. }
  23428. };
  23429. Buffer.prototype.dispose = function () {
  23430. if (!this._buffer) {
  23431. return;
  23432. }
  23433. if (this._engine._releaseBuffer(this._buffer)) {
  23434. this._buffer = null;
  23435. }
  23436. };
  23437. return Buffer;
  23438. }());
  23439. BABYLON.Buffer = Buffer;
  23440. })(BABYLON || (BABYLON = {}));
  23441. //# sourceMappingURL=babylon.buffer.js.map
  23442. var BABYLON;
  23443. (function (BABYLON) {
  23444. var VertexBuffer = /** @class */ (function () {
  23445. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23446. if (!stride) {
  23447. // Deduce stride from kind
  23448. switch (kind) {
  23449. case VertexBuffer.PositionKind:
  23450. stride = 3;
  23451. break;
  23452. case VertexBuffer.NormalKind:
  23453. stride = 3;
  23454. break;
  23455. case VertexBuffer.UVKind:
  23456. case VertexBuffer.UV2Kind:
  23457. case VertexBuffer.UV3Kind:
  23458. case VertexBuffer.UV4Kind:
  23459. case VertexBuffer.UV5Kind:
  23460. case VertexBuffer.UV6Kind:
  23461. stride = 2;
  23462. break;
  23463. case VertexBuffer.TangentKind:
  23464. case VertexBuffer.ColorKind:
  23465. stride = 4;
  23466. break;
  23467. case VertexBuffer.MatricesIndicesKind:
  23468. case VertexBuffer.MatricesIndicesExtraKind:
  23469. stride = 4;
  23470. break;
  23471. case VertexBuffer.MatricesWeightsKind:
  23472. case VertexBuffer.MatricesWeightsExtraKind:
  23473. default:
  23474. stride = 4;
  23475. break;
  23476. }
  23477. }
  23478. if (data instanceof BABYLON.Buffer) {
  23479. if (!stride) {
  23480. stride = data.getStrideSize();
  23481. }
  23482. this._buffer = data;
  23483. this._ownsBuffer = false;
  23484. }
  23485. else {
  23486. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  23487. this._ownsBuffer = true;
  23488. }
  23489. this._stride = stride;
  23490. this._offset = offset ? offset : 0;
  23491. this._size = size ? size : stride;
  23492. this._kind = kind;
  23493. }
  23494. VertexBuffer.prototype._rebuild = function () {
  23495. if (!this._buffer) {
  23496. return;
  23497. }
  23498. this._buffer._rebuild();
  23499. };
  23500. /**
  23501. * Returns the kind of the VertexBuffer (string).
  23502. */
  23503. VertexBuffer.prototype.getKind = function () {
  23504. return this._kind;
  23505. };
  23506. // Properties
  23507. /**
  23508. * Boolean : is the VertexBuffer updatable ?
  23509. */
  23510. VertexBuffer.prototype.isUpdatable = function () {
  23511. return this._buffer.isUpdatable();
  23512. };
  23513. /**
  23514. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  23515. */
  23516. VertexBuffer.prototype.getData = function () {
  23517. return this._buffer.getData();
  23518. };
  23519. /**
  23520. * Returns the WebGLBuffer associated to the VertexBuffer.
  23521. */
  23522. VertexBuffer.prototype.getBuffer = function () {
  23523. return this._buffer.getBuffer();
  23524. };
  23525. /**
  23526. * Returns the stride of the VertexBuffer (integer).
  23527. */
  23528. VertexBuffer.prototype.getStrideSize = function () {
  23529. return this._stride;
  23530. };
  23531. /**
  23532. * Returns the offset (integer).
  23533. */
  23534. VertexBuffer.prototype.getOffset = function () {
  23535. return this._offset;
  23536. };
  23537. /**
  23538. * Returns the VertexBuffer total size (integer).
  23539. */
  23540. VertexBuffer.prototype.getSize = function () {
  23541. return this._size;
  23542. };
  23543. /**
  23544. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  23545. */
  23546. VertexBuffer.prototype.getIsInstanced = function () {
  23547. return this._buffer.getIsInstanced();
  23548. };
  23549. /**
  23550. * Returns the instancing divisor, zero for non-instanced (integer).
  23551. */
  23552. VertexBuffer.prototype.getInstanceDivisor = function () {
  23553. return this._buffer.instanceDivisor;
  23554. };
  23555. // Methods
  23556. /**
  23557. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  23558. * Returns the created WebGLBuffer.
  23559. */
  23560. VertexBuffer.prototype.create = function (data) {
  23561. return this._buffer.create(data);
  23562. };
  23563. /**
  23564. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23565. * Returns the updated WebGLBuffer.
  23566. */
  23567. VertexBuffer.prototype.update = function (data) {
  23568. return this._buffer.update(data);
  23569. };
  23570. /**
  23571. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23572. * Returns the directly updated WebGLBuffer.
  23573. */
  23574. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  23575. return this._buffer.updateDirectly(data, offset);
  23576. };
  23577. /**
  23578. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  23579. */
  23580. VertexBuffer.prototype.dispose = function () {
  23581. if (this._ownsBuffer) {
  23582. this._buffer.dispose();
  23583. }
  23584. };
  23585. Object.defineProperty(VertexBuffer, "PositionKind", {
  23586. get: function () {
  23587. return VertexBuffer._PositionKind;
  23588. },
  23589. enumerable: true,
  23590. configurable: true
  23591. });
  23592. Object.defineProperty(VertexBuffer, "NormalKind", {
  23593. get: function () {
  23594. return VertexBuffer._NormalKind;
  23595. },
  23596. enumerable: true,
  23597. configurable: true
  23598. });
  23599. Object.defineProperty(VertexBuffer, "TangentKind", {
  23600. get: function () {
  23601. return VertexBuffer._TangentKind;
  23602. },
  23603. enumerable: true,
  23604. configurable: true
  23605. });
  23606. Object.defineProperty(VertexBuffer, "UVKind", {
  23607. get: function () {
  23608. return VertexBuffer._UVKind;
  23609. },
  23610. enumerable: true,
  23611. configurable: true
  23612. });
  23613. Object.defineProperty(VertexBuffer, "UV2Kind", {
  23614. get: function () {
  23615. return VertexBuffer._UV2Kind;
  23616. },
  23617. enumerable: true,
  23618. configurable: true
  23619. });
  23620. Object.defineProperty(VertexBuffer, "UV3Kind", {
  23621. get: function () {
  23622. return VertexBuffer._UV3Kind;
  23623. },
  23624. enumerable: true,
  23625. configurable: true
  23626. });
  23627. Object.defineProperty(VertexBuffer, "UV4Kind", {
  23628. get: function () {
  23629. return VertexBuffer._UV4Kind;
  23630. },
  23631. enumerable: true,
  23632. configurable: true
  23633. });
  23634. Object.defineProperty(VertexBuffer, "UV5Kind", {
  23635. get: function () {
  23636. return VertexBuffer._UV5Kind;
  23637. },
  23638. enumerable: true,
  23639. configurable: true
  23640. });
  23641. Object.defineProperty(VertexBuffer, "UV6Kind", {
  23642. get: function () {
  23643. return VertexBuffer._UV6Kind;
  23644. },
  23645. enumerable: true,
  23646. configurable: true
  23647. });
  23648. Object.defineProperty(VertexBuffer, "ColorKind", {
  23649. get: function () {
  23650. return VertexBuffer._ColorKind;
  23651. },
  23652. enumerable: true,
  23653. configurable: true
  23654. });
  23655. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  23656. get: function () {
  23657. return VertexBuffer._MatricesIndicesKind;
  23658. },
  23659. enumerable: true,
  23660. configurable: true
  23661. });
  23662. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  23663. get: function () {
  23664. return VertexBuffer._MatricesWeightsKind;
  23665. },
  23666. enumerable: true,
  23667. configurable: true
  23668. });
  23669. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  23670. get: function () {
  23671. return VertexBuffer._MatricesIndicesExtraKind;
  23672. },
  23673. enumerable: true,
  23674. configurable: true
  23675. });
  23676. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  23677. get: function () {
  23678. return VertexBuffer._MatricesWeightsExtraKind;
  23679. },
  23680. enumerable: true,
  23681. configurable: true
  23682. });
  23683. // Enums
  23684. VertexBuffer._PositionKind = "position";
  23685. VertexBuffer._NormalKind = "normal";
  23686. VertexBuffer._TangentKind = "tangent";
  23687. VertexBuffer._UVKind = "uv";
  23688. VertexBuffer._UV2Kind = "uv2";
  23689. VertexBuffer._UV3Kind = "uv3";
  23690. VertexBuffer._UV4Kind = "uv4";
  23691. VertexBuffer._UV5Kind = "uv5";
  23692. VertexBuffer._UV6Kind = "uv6";
  23693. VertexBuffer._ColorKind = "color";
  23694. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  23695. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  23696. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  23697. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  23698. return VertexBuffer;
  23699. }());
  23700. BABYLON.VertexBuffer = VertexBuffer;
  23701. })(BABYLON || (BABYLON = {}));
  23702. //# sourceMappingURL=babylon.vertexBuffer.js.map
  23703. var BABYLON;
  23704. (function (BABYLON) {
  23705. var InternalTexture = /** @class */ (function () {
  23706. function InternalTexture(engine, dataSource) {
  23707. this.onLoadedObservable = new BABYLON.Observable();
  23708. // Private
  23709. this._initialSlot = -1;
  23710. this._designatedSlot = -1;
  23711. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  23712. this._references = 1;
  23713. this._engine = engine;
  23714. this._dataSource = dataSource;
  23715. this._webGLTexture = engine._createTexture();
  23716. }
  23717. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  23718. get: function () {
  23719. return this._dataSource;
  23720. },
  23721. enumerable: true,
  23722. configurable: true
  23723. });
  23724. InternalTexture.prototype.incrementReferences = function () {
  23725. this._references++;
  23726. };
  23727. InternalTexture.prototype.updateSize = function (width, height, depth) {
  23728. if (depth === void 0) { depth = 1; }
  23729. this.width = width;
  23730. this.height = height;
  23731. this.depth = depth;
  23732. this.baseWidth = width;
  23733. this.baseHeight = height;
  23734. this.baseDepth = depth;
  23735. this._size = width * height * depth;
  23736. };
  23737. InternalTexture.prototype._rebuild = function () {
  23738. var _this = this;
  23739. var proxy;
  23740. this.isReady = false;
  23741. this._cachedCoordinatesMode = null;
  23742. this._cachedWrapU = null;
  23743. this._cachedWrapV = null;
  23744. this._cachedAnisotropicFilteringLevel = null;
  23745. switch (this._dataSource) {
  23746. case InternalTexture.DATASOURCE_TEMP:
  23747. return;
  23748. case InternalTexture.DATASOURCE_URL:
  23749. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  23750. _this.isReady = true;
  23751. }, null, this._buffer, undefined, this.format);
  23752. proxy._swapAndDie(this);
  23753. return;
  23754. case InternalTexture.DATASOURCE_RAW:
  23755. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23756. proxy._swapAndDie(this);
  23757. this.isReady = true;
  23758. return;
  23759. case InternalTexture.DATASOURCE_RAW3D:
  23760. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23761. proxy._swapAndDie(this);
  23762. this.isReady = true;
  23763. return;
  23764. case InternalTexture.DATASOURCE_DYNAMIC:
  23765. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  23766. proxy._swapAndDie(this);
  23767. // The engine will make sure to update content so no need to flag it as isReady = true
  23768. return;
  23769. case InternalTexture.DATASOURCE_RENDERTARGET:
  23770. var options = new BABYLON.RenderTargetCreationOptions();
  23771. options.generateDepthBuffer = this._generateDepthBuffer;
  23772. options.generateMipMaps = this.generateMipMaps;
  23773. options.generateStencilBuffer = this._generateStencilBuffer;
  23774. options.samplingMode = this.samplingMode;
  23775. options.type = this.type;
  23776. if (this.isCube) {
  23777. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  23778. }
  23779. else {
  23780. var size = {
  23781. width: this.width,
  23782. height: this.height
  23783. };
  23784. proxy = this._engine.createRenderTargetTexture(size, options);
  23785. }
  23786. proxy._swapAndDie(this);
  23787. this.isReady = true;
  23788. return;
  23789. case InternalTexture.DATASOURCE_CUBE:
  23790. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  23791. _this.isReady = true;
  23792. }, null, this.format, this._extension);
  23793. proxy._swapAndDie(this);
  23794. return;
  23795. case InternalTexture.DATASOURCE_CUBERAW:
  23796. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23797. proxy._swapAndDie(this);
  23798. this.isReady = true;
  23799. return;
  23800. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  23801. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  23802. if (proxy) {
  23803. proxy._swapAndDie(_this);
  23804. }
  23805. _this.isReady = true;
  23806. }, null, this.format, this._extension);
  23807. return;
  23808. }
  23809. };
  23810. InternalTexture.prototype._swapAndDie = function (target) {
  23811. target._webGLTexture = this._webGLTexture;
  23812. if (this._framebuffer) {
  23813. target._framebuffer = this._framebuffer;
  23814. }
  23815. if (this._depthStencilBuffer) {
  23816. target._depthStencilBuffer = this._depthStencilBuffer;
  23817. }
  23818. if (this._lodTextureHigh) {
  23819. if (target._lodTextureHigh) {
  23820. target._lodTextureHigh.dispose();
  23821. }
  23822. target._lodTextureHigh = this._lodTextureHigh;
  23823. }
  23824. if (this._lodTextureMid) {
  23825. if (target._lodTextureMid) {
  23826. target._lodTextureMid.dispose();
  23827. }
  23828. target._lodTextureMid = this._lodTextureMid;
  23829. }
  23830. if (this._lodTextureLow) {
  23831. if (target._lodTextureLow) {
  23832. target._lodTextureLow.dispose();
  23833. }
  23834. target._lodTextureLow = this._lodTextureLow;
  23835. }
  23836. var cache = this._engine.getLoadedTexturesCache();
  23837. var index = cache.indexOf(this);
  23838. if (index !== -1) {
  23839. cache.splice(index, 1);
  23840. }
  23841. };
  23842. InternalTexture.prototype.dispose = function () {
  23843. if (!this._webGLTexture) {
  23844. return;
  23845. }
  23846. this._references--;
  23847. if (this._references === 0) {
  23848. this._engine._releaseTexture(this);
  23849. this._webGLTexture = null;
  23850. }
  23851. };
  23852. InternalTexture.DATASOURCE_UNKNOWN = 0;
  23853. InternalTexture.DATASOURCE_URL = 1;
  23854. InternalTexture.DATASOURCE_TEMP = 2;
  23855. InternalTexture.DATASOURCE_RAW = 3;
  23856. InternalTexture.DATASOURCE_DYNAMIC = 4;
  23857. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  23858. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  23859. InternalTexture.DATASOURCE_CUBE = 7;
  23860. InternalTexture.DATASOURCE_CUBERAW = 8;
  23861. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  23862. InternalTexture.DATASOURCE_RAW3D = 10;
  23863. return InternalTexture;
  23864. }());
  23865. BABYLON.InternalTexture = InternalTexture;
  23866. })(BABYLON || (BABYLON = {}));
  23867. //# sourceMappingURL=babylon.internalTexture.js.map
  23868. var BABYLON;
  23869. (function (BABYLON) {
  23870. var BaseTexture = /** @class */ (function () {
  23871. function BaseTexture(scene) {
  23872. this._hasAlpha = false;
  23873. this.getAlphaFromRGB = false;
  23874. this.level = 1;
  23875. this.coordinatesIndex = 0;
  23876. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23877. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23878. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23879. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  23880. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  23881. this.isCube = false;
  23882. this.is3D = false;
  23883. this.gammaSpace = true;
  23884. this.invertZ = false;
  23885. this.lodLevelInAlpha = false;
  23886. this.lodGenerationOffset = 0.0;
  23887. this.lodGenerationScale = 0.8;
  23888. this.isRenderTarget = false;
  23889. this.animations = new Array();
  23890. /**
  23891. * An event triggered when the texture is disposed.
  23892. * @type {BABYLON.Observable}
  23893. */
  23894. this.onDisposeObservable = new BABYLON.Observable();
  23895. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23896. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23897. if (this._scene) {
  23898. this._scene.textures.push(this);
  23899. }
  23900. this._uid = null;
  23901. }
  23902. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  23903. get: function () {
  23904. return this._hasAlpha;
  23905. },
  23906. set: function (value) {
  23907. if (this._hasAlpha === value) {
  23908. return;
  23909. }
  23910. this._hasAlpha = value;
  23911. if (this._scene) {
  23912. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23913. }
  23914. },
  23915. enumerable: true,
  23916. configurable: true
  23917. });
  23918. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  23919. get: function () {
  23920. return this._coordinatesMode;
  23921. },
  23922. set: function (value) {
  23923. if (this._coordinatesMode === value) {
  23924. return;
  23925. }
  23926. this._coordinatesMode = value;
  23927. if (this._scene) {
  23928. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23929. }
  23930. },
  23931. enumerable: true,
  23932. configurable: true
  23933. });
  23934. Object.defineProperty(BaseTexture.prototype, "uid", {
  23935. get: function () {
  23936. if (!this._uid) {
  23937. this._uid = BABYLON.Tools.RandomId();
  23938. }
  23939. return this._uid;
  23940. },
  23941. enumerable: true,
  23942. configurable: true
  23943. });
  23944. BaseTexture.prototype.toString = function () {
  23945. return this.name;
  23946. };
  23947. BaseTexture.prototype.getClassName = function () {
  23948. return "BaseTexture";
  23949. };
  23950. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23951. set: function (callback) {
  23952. if (this._onDisposeObserver) {
  23953. this.onDisposeObservable.remove(this._onDisposeObserver);
  23954. }
  23955. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23956. },
  23957. enumerable: true,
  23958. configurable: true
  23959. });
  23960. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  23961. get: function () {
  23962. return true;
  23963. },
  23964. enumerable: true,
  23965. configurable: true
  23966. });
  23967. BaseTexture.prototype.getScene = function () {
  23968. return this._scene;
  23969. };
  23970. BaseTexture.prototype.getTextureMatrix = function () {
  23971. return BABYLON.Matrix.IdentityReadOnly;
  23972. };
  23973. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23974. return BABYLON.Matrix.IdentityReadOnly;
  23975. };
  23976. BaseTexture.prototype.getInternalTexture = function () {
  23977. return this._texture;
  23978. };
  23979. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  23980. return !this.isBlocking || this.isReady();
  23981. };
  23982. BaseTexture.prototype.isReady = function () {
  23983. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23984. this.delayLoad();
  23985. return false;
  23986. }
  23987. if (this._texture) {
  23988. return this._texture.isReady;
  23989. }
  23990. return false;
  23991. };
  23992. BaseTexture.prototype.getSize = function () {
  23993. if (this._texture && this._texture.width) {
  23994. return new BABYLON.Size(this._texture.width, this._texture.height);
  23995. }
  23996. if (this._texture && this._texture._size) {
  23997. return new BABYLON.Size(this._texture._size, this._texture._size);
  23998. }
  23999. return BABYLON.Size.Zero();
  24000. };
  24001. BaseTexture.prototype.getBaseSize = function () {
  24002. if (!this.isReady() || !this._texture)
  24003. return BABYLON.Size.Zero();
  24004. if (this._texture._size) {
  24005. return new BABYLON.Size(this._texture._size, this._texture._size);
  24006. }
  24007. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  24008. };
  24009. BaseTexture.prototype.scale = function (ratio) {
  24010. };
  24011. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  24012. get: function () {
  24013. return false;
  24014. },
  24015. enumerable: true,
  24016. configurable: true
  24017. });
  24018. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  24019. if (!this._scene) {
  24020. return null;
  24021. }
  24022. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24023. for (var index = 0; index < texturesCache.length; index++) {
  24024. var texturesCacheEntry = texturesCache[index];
  24025. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  24026. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  24027. texturesCacheEntry.incrementReferences();
  24028. return texturesCacheEntry;
  24029. }
  24030. }
  24031. }
  24032. return null;
  24033. };
  24034. BaseTexture.prototype._rebuild = function () {
  24035. };
  24036. BaseTexture.prototype.delayLoad = function () {
  24037. };
  24038. BaseTexture.prototype.clone = function () {
  24039. return null;
  24040. };
  24041. Object.defineProperty(BaseTexture.prototype, "textureType", {
  24042. get: function () {
  24043. if (!this._texture) {
  24044. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24045. }
  24046. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24047. },
  24048. enumerable: true,
  24049. configurable: true
  24050. });
  24051. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  24052. get: function () {
  24053. if (!this._texture) {
  24054. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24055. }
  24056. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24057. },
  24058. enumerable: true,
  24059. configurable: true
  24060. });
  24061. BaseTexture.prototype.readPixels = function (faceIndex) {
  24062. if (faceIndex === void 0) { faceIndex = 0; }
  24063. if (!this._texture) {
  24064. return null;
  24065. }
  24066. var size = this.getSize();
  24067. var scene = this.getScene();
  24068. if (!scene) {
  24069. return null;
  24070. }
  24071. var engine = scene.getEngine();
  24072. if (this._texture.isCube) {
  24073. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  24074. }
  24075. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  24076. };
  24077. BaseTexture.prototype.releaseInternalTexture = function () {
  24078. if (this._texture) {
  24079. this._texture.dispose();
  24080. this._texture = null;
  24081. }
  24082. };
  24083. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  24084. get: function () {
  24085. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  24086. return null;
  24087. }
  24088. if (!this._texture._sphericalPolynomial) {
  24089. this._texture._sphericalPolynomial =
  24090. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  24091. }
  24092. return this._texture._sphericalPolynomial;
  24093. },
  24094. set: function (value) {
  24095. if (this._texture) {
  24096. this._texture._sphericalPolynomial = value;
  24097. }
  24098. },
  24099. enumerable: true,
  24100. configurable: true
  24101. });
  24102. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  24103. get: function () {
  24104. if (this._texture) {
  24105. return this._texture._lodTextureHigh;
  24106. }
  24107. return null;
  24108. },
  24109. enumerable: true,
  24110. configurable: true
  24111. });
  24112. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  24113. get: function () {
  24114. if (this._texture) {
  24115. return this._texture._lodTextureMid;
  24116. }
  24117. return null;
  24118. },
  24119. enumerable: true,
  24120. configurable: true
  24121. });
  24122. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  24123. get: function () {
  24124. if (this._texture) {
  24125. return this._texture._lodTextureLow;
  24126. }
  24127. return null;
  24128. },
  24129. enumerable: true,
  24130. configurable: true
  24131. });
  24132. BaseTexture.prototype.dispose = function () {
  24133. if (!this._scene) {
  24134. return;
  24135. }
  24136. // Animations
  24137. this._scene.stopAnimation(this);
  24138. // Remove from scene
  24139. this._scene._removePendingData(this);
  24140. var index = this._scene.textures.indexOf(this);
  24141. if (index >= 0) {
  24142. this._scene.textures.splice(index, 1);
  24143. }
  24144. if (this._texture === undefined) {
  24145. return;
  24146. }
  24147. // Release
  24148. this.releaseInternalTexture();
  24149. // Callback
  24150. this.onDisposeObservable.notifyObservers(this);
  24151. this.onDisposeObservable.clear();
  24152. };
  24153. BaseTexture.prototype.serialize = function () {
  24154. if (!this.name) {
  24155. return null;
  24156. }
  24157. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24158. // Animations
  24159. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24160. return serializationObject;
  24161. };
  24162. BaseTexture.WhenAllReady = function (textures, callback) {
  24163. var numRemaining = textures.length;
  24164. if (numRemaining === 0) {
  24165. callback();
  24166. return;
  24167. }
  24168. var _loop_1 = function () {
  24169. texture = textures[i];
  24170. if (texture.isReady()) {
  24171. if (--numRemaining === 0) {
  24172. callback();
  24173. }
  24174. }
  24175. else {
  24176. onLoadObservable = texture.onLoadObservable;
  24177. var onLoadCallback_1 = function () {
  24178. onLoadObservable.removeCallback(onLoadCallback_1);
  24179. if (--numRemaining === 0) {
  24180. callback();
  24181. }
  24182. };
  24183. onLoadObservable.add(onLoadCallback_1);
  24184. }
  24185. };
  24186. var texture, onLoadObservable;
  24187. for (var i = 0; i < textures.length; i++) {
  24188. _loop_1();
  24189. }
  24190. };
  24191. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  24192. __decorate([
  24193. BABYLON.serialize()
  24194. ], BaseTexture.prototype, "name", void 0);
  24195. __decorate([
  24196. BABYLON.serialize("hasAlpha")
  24197. ], BaseTexture.prototype, "_hasAlpha", void 0);
  24198. __decorate([
  24199. BABYLON.serialize()
  24200. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  24201. __decorate([
  24202. BABYLON.serialize()
  24203. ], BaseTexture.prototype, "level", void 0);
  24204. __decorate([
  24205. BABYLON.serialize()
  24206. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  24207. __decorate([
  24208. BABYLON.serialize("coordinatesMode")
  24209. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  24210. __decorate([
  24211. BABYLON.serialize()
  24212. ], BaseTexture.prototype, "wrapU", void 0);
  24213. __decorate([
  24214. BABYLON.serialize()
  24215. ], BaseTexture.prototype, "wrapV", void 0);
  24216. __decorate([
  24217. BABYLON.serialize()
  24218. ], BaseTexture.prototype, "wrapR", void 0);
  24219. __decorate([
  24220. BABYLON.serialize()
  24221. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  24222. __decorate([
  24223. BABYLON.serialize()
  24224. ], BaseTexture.prototype, "isCube", void 0);
  24225. __decorate([
  24226. BABYLON.serialize()
  24227. ], BaseTexture.prototype, "is3D", void 0);
  24228. __decorate([
  24229. BABYLON.serialize()
  24230. ], BaseTexture.prototype, "gammaSpace", void 0);
  24231. __decorate([
  24232. BABYLON.serialize()
  24233. ], BaseTexture.prototype, "invertZ", void 0);
  24234. __decorate([
  24235. BABYLON.serialize()
  24236. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  24237. __decorate([
  24238. BABYLON.serialize()
  24239. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  24240. __decorate([
  24241. BABYLON.serialize()
  24242. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  24243. __decorate([
  24244. BABYLON.serialize()
  24245. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24246. return BaseTexture;
  24247. }());
  24248. BABYLON.BaseTexture = BaseTexture;
  24249. })(BABYLON || (BABYLON = {}));
  24250. //# sourceMappingURL=babylon.baseTexture.js.map
  24251. var BABYLON;
  24252. (function (BABYLON) {
  24253. var Texture = /** @class */ (function (_super) {
  24254. __extends(Texture, _super);
  24255. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  24256. if (noMipmap === void 0) { noMipmap = false; }
  24257. if (invertY === void 0) { invertY = true; }
  24258. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24259. if (onLoad === void 0) { onLoad = null; }
  24260. if (onError === void 0) { onError = null; }
  24261. if (buffer === void 0) { buffer = null; }
  24262. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24263. var _this = _super.call(this, scene) || this;
  24264. _this.uOffset = 0;
  24265. _this.vOffset = 0;
  24266. _this.uScale = 1.0;
  24267. _this.vScale = 1.0;
  24268. _this.uAng = 0;
  24269. _this.vAng = 0;
  24270. _this.wAng = 0;
  24271. _this._isBlocking = true;
  24272. _this.name = url || "";
  24273. _this.url = url;
  24274. _this._noMipmap = noMipmap;
  24275. _this._invertY = invertY;
  24276. _this._samplingMode = samplingMode;
  24277. _this._buffer = buffer;
  24278. _this._deleteBuffer = deleteBuffer;
  24279. if (format) {
  24280. _this._format = format;
  24281. }
  24282. scene = _this.getScene();
  24283. if (!scene) {
  24284. return _this;
  24285. }
  24286. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  24287. var load = function () {
  24288. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  24289. _this.onLoadObservable.notifyObservers(_this);
  24290. }
  24291. if (onLoad) {
  24292. onLoad();
  24293. }
  24294. if (!_this.isBlocking && scene) {
  24295. scene.resetCachedMaterial();
  24296. }
  24297. };
  24298. if (!_this.url) {
  24299. _this._delayedOnLoad = load;
  24300. _this._delayedOnError = onError;
  24301. return _this;
  24302. }
  24303. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  24304. if (!_this._texture) {
  24305. if (!scene.useDelayedTextureLoading) {
  24306. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  24307. if (deleteBuffer) {
  24308. delete _this._buffer;
  24309. }
  24310. }
  24311. else {
  24312. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24313. _this._delayedOnLoad = load;
  24314. _this._delayedOnError = onError;
  24315. }
  24316. }
  24317. else {
  24318. if (_this._texture.isReady) {
  24319. BABYLON.Tools.SetImmediate(function () { return load(); });
  24320. }
  24321. else {
  24322. _this._texture.onLoadedObservable.add(load);
  24323. }
  24324. }
  24325. return _this;
  24326. }
  24327. Object.defineProperty(Texture.prototype, "noMipmap", {
  24328. get: function () {
  24329. return this._noMipmap;
  24330. },
  24331. enumerable: true,
  24332. configurable: true
  24333. });
  24334. Object.defineProperty(Texture.prototype, "isBlocking", {
  24335. get: function () {
  24336. return this._isBlocking;
  24337. },
  24338. set: function (value) {
  24339. this._isBlocking = value;
  24340. },
  24341. enumerable: true,
  24342. configurable: true
  24343. });
  24344. Object.defineProperty(Texture.prototype, "samplingMode", {
  24345. get: function () {
  24346. return this._samplingMode;
  24347. },
  24348. enumerable: true,
  24349. configurable: true
  24350. });
  24351. Texture.prototype.updateURL = function (url) {
  24352. this.url = url;
  24353. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24354. this.delayLoad();
  24355. };
  24356. Texture.prototype.delayLoad = function () {
  24357. var _this = this;
  24358. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24359. return;
  24360. }
  24361. var scene = this.getScene();
  24362. if (!scene) {
  24363. return;
  24364. }
  24365. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24366. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24367. if (!this._texture) {
  24368. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  24369. if (this._deleteBuffer) {
  24370. delete this._buffer;
  24371. }
  24372. }
  24373. else {
  24374. if (this._texture.isReady) {
  24375. BABYLON.Tools.SetImmediate(function () {
  24376. if (!_this._delayedOnLoad) {
  24377. return;
  24378. }
  24379. _this._delayedOnLoad();
  24380. });
  24381. }
  24382. else {
  24383. if (this._delayedOnLoad) {
  24384. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  24385. }
  24386. }
  24387. }
  24388. };
  24389. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24390. if (!this._texture) {
  24391. return;
  24392. }
  24393. var scene = this.getScene();
  24394. if (!scene) {
  24395. return;
  24396. }
  24397. this._samplingMode = samplingMode;
  24398. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24399. };
  24400. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24401. x *= this.uScale;
  24402. y *= this.vScale;
  24403. x -= 0.5 * this.uScale;
  24404. y -= 0.5 * this.vScale;
  24405. z -= 0.5;
  24406. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24407. t.x += 0.5 * this.uScale + this.uOffset;
  24408. t.y += 0.5 * this.vScale + this.vOffset;
  24409. t.z += 0.5;
  24410. };
  24411. Texture.prototype.getTextureMatrix = function () {
  24412. var _this = this;
  24413. if (this.uOffset === this._cachedUOffset &&
  24414. this.vOffset === this._cachedVOffset &&
  24415. this.uScale === this._cachedUScale &&
  24416. this.vScale === this._cachedVScale &&
  24417. this.uAng === this._cachedUAng &&
  24418. this.vAng === this._cachedVAng &&
  24419. this.wAng === this._cachedWAng) {
  24420. return this._cachedTextureMatrix;
  24421. }
  24422. this._cachedUOffset = this.uOffset;
  24423. this._cachedVOffset = this.vOffset;
  24424. this._cachedUScale = this.uScale;
  24425. this._cachedVScale = this.vScale;
  24426. this._cachedUAng = this.uAng;
  24427. this._cachedVAng = this.vAng;
  24428. this._cachedWAng = this.wAng;
  24429. if (!this._cachedTextureMatrix) {
  24430. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24431. this._rowGenerationMatrix = new BABYLON.Matrix();
  24432. this._t0 = BABYLON.Vector3.Zero();
  24433. this._t1 = BABYLON.Vector3.Zero();
  24434. this._t2 = BABYLON.Vector3.Zero();
  24435. }
  24436. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24437. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24438. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24439. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24440. this._t1.subtractInPlace(this._t0);
  24441. this._t2.subtractInPlace(this._t0);
  24442. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24443. this._cachedTextureMatrix.m[0] = this._t1.x;
  24444. this._cachedTextureMatrix.m[1] = this._t1.y;
  24445. this._cachedTextureMatrix.m[2] = this._t1.z;
  24446. this._cachedTextureMatrix.m[4] = this._t2.x;
  24447. this._cachedTextureMatrix.m[5] = this._t2.y;
  24448. this._cachedTextureMatrix.m[6] = this._t2.z;
  24449. this._cachedTextureMatrix.m[8] = this._t0.x;
  24450. this._cachedTextureMatrix.m[9] = this._t0.y;
  24451. this._cachedTextureMatrix.m[10] = this._t0.z;
  24452. var scene = this.getScene();
  24453. if (!scene) {
  24454. return this._cachedTextureMatrix;
  24455. }
  24456. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24457. return mat.hasTexture(_this);
  24458. });
  24459. return this._cachedTextureMatrix;
  24460. };
  24461. Texture.prototype.getReflectionTextureMatrix = function () {
  24462. var _this = this;
  24463. var scene = this.getScene();
  24464. if (!scene) {
  24465. return this._cachedTextureMatrix;
  24466. }
  24467. if (this.uOffset === this._cachedUOffset &&
  24468. this.vOffset === this._cachedVOffset &&
  24469. this.uScale === this._cachedUScale &&
  24470. this.vScale === this._cachedVScale &&
  24471. this.coordinatesMode === this._cachedCoordinatesMode) {
  24472. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  24473. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  24474. return this._cachedTextureMatrix;
  24475. }
  24476. }
  24477. else {
  24478. return this._cachedTextureMatrix;
  24479. }
  24480. }
  24481. if (!this._cachedTextureMatrix) {
  24482. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24483. }
  24484. if (!this._projectionModeMatrix) {
  24485. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24486. }
  24487. this._cachedUOffset = this.uOffset;
  24488. this._cachedVOffset = this.vOffset;
  24489. this._cachedUScale = this.uScale;
  24490. this._cachedVScale = this.vScale;
  24491. this._cachedCoordinatesMode = this.coordinatesMode;
  24492. switch (this.coordinatesMode) {
  24493. case Texture.PLANAR_MODE:
  24494. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24495. this._cachedTextureMatrix[0] = this.uScale;
  24496. this._cachedTextureMatrix[5] = this.vScale;
  24497. this._cachedTextureMatrix[12] = this.uOffset;
  24498. this._cachedTextureMatrix[13] = this.vOffset;
  24499. break;
  24500. case Texture.PROJECTION_MODE:
  24501. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24502. this._projectionModeMatrix.m[0] = 0.5;
  24503. this._projectionModeMatrix.m[5] = -0.5;
  24504. this._projectionModeMatrix.m[10] = 0.0;
  24505. this._projectionModeMatrix.m[12] = 0.5;
  24506. this._projectionModeMatrix.m[13] = 0.5;
  24507. this._projectionModeMatrix.m[14] = 1.0;
  24508. this._projectionModeMatrix.m[15] = 1.0;
  24509. var projectionMatrix = scene.getProjectionMatrix();
  24510. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  24511. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24512. break;
  24513. default:
  24514. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24515. break;
  24516. }
  24517. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24518. return (mat.getActiveTextures().indexOf(_this) !== -1);
  24519. });
  24520. return this._cachedTextureMatrix;
  24521. };
  24522. Texture.prototype.clone = function () {
  24523. var _this = this;
  24524. return BABYLON.SerializationHelper.Clone(function () {
  24525. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24526. }, this);
  24527. };
  24528. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24529. get: function () {
  24530. if (!this._onLoadObservable) {
  24531. this._onLoadObservable = new BABYLON.Observable();
  24532. }
  24533. return this._onLoadObservable;
  24534. },
  24535. enumerable: true,
  24536. configurable: true
  24537. });
  24538. Texture.prototype.serialize = function () {
  24539. var serializationObject = _super.prototype.serialize.call(this);
  24540. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  24541. serializationObject.base64String = this._buffer;
  24542. serializationObject.name = serializationObject.name.replace("data:", "");
  24543. }
  24544. return serializationObject;
  24545. };
  24546. Texture.prototype.getClassName = function () {
  24547. return "Texture";
  24548. };
  24549. Texture.prototype.dispose = function () {
  24550. _super.prototype.dispose.call(this);
  24551. if (this.onLoadObservable) {
  24552. this.onLoadObservable.clear();
  24553. this._onLoadObservable = null;
  24554. }
  24555. this._delayedOnLoad = null;
  24556. this._delayedOnError = null;
  24557. };
  24558. // Statics
  24559. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24560. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24561. if (onLoad === void 0) { onLoad = null; }
  24562. if (onError === void 0) { onError = null; }
  24563. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24564. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  24565. };
  24566. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24567. if (parsedTexture.customType) {
  24568. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24569. // Update Sampling Mode
  24570. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  24571. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  24572. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  24573. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  24574. }
  24575. }
  24576. return parsedCustomTexture;
  24577. }
  24578. if (parsedTexture.isCube) {
  24579. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24580. }
  24581. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24582. return null;
  24583. }
  24584. var texture = BABYLON.SerializationHelper.Parse(function () {
  24585. var generateMipMaps = true;
  24586. if (parsedTexture.noMipmap) {
  24587. generateMipMaps = false;
  24588. }
  24589. if (parsedTexture.mirrorPlane) {
  24590. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24591. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24592. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24593. return mirrorTexture;
  24594. }
  24595. else if (parsedTexture.isRenderTarget) {
  24596. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24597. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24598. return renderTargetTexture;
  24599. }
  24600. else {
  24601. var texture;
  24602. if (parsedTexture.base64String) {
  24603. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  24604. }
  24605. else {
  24606. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  24607. }
  24608. return texture;
  24609. }
  24610. }, parsedTexture, scene);
  24611. // Update Sampling Mode
  24612. if (parsedTexture.samplingMode) {
  24613. var sampling = parsedTexture.samplingMode;
  24614. if (texture._samplingMode !== sampling) {
  24615. texture.updateSamplingMode(sampling);
  24616. }
  24617. }
  24618. // Animations
  24619. if (parsedTexture.animations) {
  24620. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24621. var parsedAnimation = parsedTexture.animations[animationIndex];
  24622. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24623. }
  24624. }
  24625. return texture;
  24626. };
  24627. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24628. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24629. if (noMipmap === void 0) { noMipmap = false; }
  24630. if (invertY === void 0) { invertY = true; }
  24631. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24632. if (onLoad === void 0) { onLoad = null; }
  24633. if (onError === void 0) { onError = null; }
  24634. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24635. if (name.substr(0, 5) !== "data:") {
  24636. name = "data:" + name;
  24637. }
  24638. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  24639. };
  24640. // Constants
  24641. Texture.NEAREST_SAMPLINGMODE = 1;
  24642. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  24643. Texture.BILINEAR_SAMPLINGMODE = 2;
  24644. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  24645. Texture.TRILINEAR_SAMPLINGMODE = 3;
  24646. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  24647. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  24648. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  24649. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  24650. Texture.NEAREST_LINEAR = 7;
  24651. Texture.NEAREST_NEAREST = 8;
  24652. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  24653. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  24654. Texture.LINEAR_LINEAR = 11;
  24655. Texture.LINEAR_NEAREST = 12;
  24656. Texture.EXPLICIT_MODE = 0;
  24657. Texture.SPHERICAL_MODE = 1;
  24658. Texture.PLANAR_MODE = 2;
  24659. Texture.CUBIC_MODE = 3;
  24660. Texture.PROJECTION_MODE = 4;
  24661. Texture.SKYBOX_MODE = 5;
  24662. Texture.INVCUBIC_MODE = 6;
  24663. Texture.EQUIRECTANGULAR_MODE = 7;
  24664. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  24665. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  24666. Texture.CLAMP_ADDRESSMODE = 0;
  24667. Texture.WRAP_ADDRESSMODE = 1;
  24668. Texture.MIRROR_ADDRESSMODE = 2;
  24669. __decorate([
  24670. BABYLON.serialize()
  24671. ], Texture.prototype, "url", void 0);
  24672. __decorate([
  24673. BABYLON.serialize()
  24674. ], Texture.prototype, "uOffset", void 0);
  24675. __decorate([
  24676. BABYLON.serialize()
  24677. ], Texture.prototype, "vOffset", void 0);
  24678. __decorate([
  24679. BABYLON.serialize()
  24680. ], Texture.prototype, "uScale", void 0);
  24681. __decorate([
  24682. BABYLON.serialize()
  24683. ], Texture.prototype, "vScale", void 0);
  24684. __decorate([
  24685. BABYLON.serialize()
  24686. ], Texture.prototype, "uAng", void 0);
  24687. __decorate([
  24688. BABYLON.serialize()
  24689. ], Texture.prototype, "vAng", void 0);
  24690. __decorate([
  24691. BABYLON.serialize()
  24692. ], Texture.prototype, "wAng", void 0);
  24693. __decorate([
  24694. BABYLON.serialize()
  24695. ], Texture.prototype, "isBlocking", null);
  24696. return Texture;
  24697. }(BABYLON.BaseTexture));
  24698. BABYLON.Texture = Texture;
  24699. })(BABYLON || (BABYLON = {}));
  24700. //# sourceMappingURL=babylon.texture.js.map
  24701. var BABYLON;
  24702. (function (BABYLON) {
  24703. var _InstancesBatch = /** @class */ (function () {
  24704. function _InstancesBatch() {
  24705. this.mustReturn = false;
  24706. this.visibleInstances = new Array();
  24707. this.renderSelf = new Array();
  24708. }
  24709. return _InstancesBatch;
  24710. }());
  24711. BABYLON._InstancesBatch = _InstancesBatch;
  24712. var Mesh = /** @class */ (function (_super) {
  24713. __extends(Mesh, _super);
  24714. /**
  24715. * @constructor
  24716. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  24717. * @param {Scene} scene The scene to add this mesh to.
  24718. * @param {Node} parent The parent of this mesh, if it has one
  24719. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  24720. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  24721. * When false, achieved by calling a clone(), also passing False.
  24722. * This will make creation of children, recursive.
  24723. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  24724. */
  24725. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  24726. if (scene === void 0) { scene = null; }
  24727. if (parent === void 0) { parent = null; }
  24728. if (source === void 0) { source = null; }
  24729. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24730. var _this = _super.call(this, name, scene) || this;
  24731. // Events
  24732. /**
  24733. * An event triggered before rendering the mesh
  24734. * @type {BABYLON.Observable}
  24735. */
  24736. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24737. /**
  24738. * An event triggered after rendering the mesh
  24739. * @type {BABYLON.Observable}
  24740. */
  24741. _this.onAfterRenderObservable = new BABYLON.Observable();
  24742. /**
  24743. * An event triggered before drawing the mesh
  24744. * @type {BABYLON.Observable}
  24745. */
  24746. _this.onBeforeDrawObservable = new BABYLON.Observable();
  24747. // Members
  24748. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24749. _this.instances = new Array();
  24750. _this._LODLevels = new Array();
  24751. _this._visibleInstances = {};
  24752. _this._renderIdForInstances = new Array();
  24753. _this._batchCache = new _InstancesBatch();
  24754. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  24755. // Use by builder only to know what orientation were the mesh build in.
  24756. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  24757. _this.overrideMaterialSideOrientation = null;
  24758. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  24759. // Will be used to save a source mesh reference, If any
  24760. _this._source = null;
  24761. scene = _this.getScene();
  24762. if (source) {
  24763. // Source mesh
  24764. _this._source = source;
  24765. // Geometry
  24766. if (source._geometry) {
  24767. source._geometry.applyToMesh(_this);
  24768. }
  24769. // Deep copy
  24770. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  24771. // Metadata
  24772. if (source.metadata && source.metadata.clone) {
  24773. _this.metadata = source.metadata.clone();
  24774. }
  24775. else {
  24776. _this.metadata = source.metadata;
  24777. }
  24778. // Tags
  24779. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  24780. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  24781. }
  24782. // Parent
  24783. _this.parent = source.parent;
  24784. // Pivot
  24785. _this.setPivotMatrix(source.getPivotMatrix());
  24786. _this.id = name + "." + source.id;
  24787. // Material
  24788. _this.material = source.material;
  24789. var index;
  24790. if (!doNotCloneChildren) {
  24791. // Children
  24792. var directDescendants = source.getDescendants(true);
  24793. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  24794. var child = directDescendants[index_1];
  24795. if (child.clone) {
  24796. child.clone(name + "." + child.name, _this);
  24797. }
  24798. }
  24799. }
  24800. // Physics clone
  24801. var physicsEngine = _this.getScene().getPhysicsEngine();
  24802. if (clonePhysicsImpostor && physicsEngine) {
  24803. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  24804. if (impostor) {
  24805. _this.physicsImpostor = impostor.clone(_this);
  24806. }
  24807. }
  24808. // Particles
  24809. for (index = 0; index < scene.particleSystems.length; index++) {
  24810. var system = scene.particleSystems[index];
  24811. if (system.emitter === source) {
  24812. system.clone(system.name, _this);
  24813. }
  24814. }
  24815. _this.computeWorldMatrix(true);
  24816. }
  24817. // Parent
  24818. if (parent !== null) {
  24819. _this.parent = parent;
  24820. }
  24821. return _this;
  24822. }
  24823. Object.defineProperty(Mesh, "FRONTSIDE", {
  24824. /**
  24825. * Mesh side orientation : usually the external or front surface
  24826. */
  24827. get: function () {
  24828. return Mesh._FRONTSIDE;
  24829. },
  24830. enumerable: true,
  24831. configurable: true
  24832. });
  24833. Object.defineProperty(Mesh, "BACKSIDE", {
  24834. /**
  24835. * Mesh side orientation : usually the internal or back surface
  24836. */
  24837. get: function () {
  24838. return Mesh._BACKSIDE;
  24839. },
  24840. enumerable: true,
  24841. configurable: true
  24842. });
  24843. Object.defineProperty(Mesh, "DOUBLESIDE", {
  24844. /**
  24845. * Mesh side orientation : both internal and external or front and back surfaces
  24846. */
  24847. get: function () {
  24848. return Mesh._DOUBLESIDE;
  24849. },
  24850. enumerable: true,
  24851. configurable: true
  24852. });
  24853. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  24854. /**
  24855. * Mesh side orientation : by default, `FRONTSIDE`
  24856. */
  24857. get: function () {
  24858. return Mesh._DEFAULTSIDE;
  24859. },
  24860. enumerable: true,
  24861. configurable: true
  24862. });
  24863. Object.defineProperty(Mesh, "NO_CAP", {
  24864. /**
  24865. * Mesh cap setting : no cap
  24866. */
  24867. get: function () {
  24868. return Mesh._NO_CAP;
  24869. },
  24870. enumerable: true,
  24871. configurable: true
  24872. });
  24873. Object.defineProperty(Mesh, "CAP_START", {
  24874. /**
  24875. * Mesh cap setting : one cap at the beginning of the mesh
  24876. */
  24877. get: function () {
  24878. return Mesh._CAP_START;
  24879. },
  24880. enumerable: true,
  24881. configurable: true
  24882. });
  24883. Object.defineProperty(Mesh, "CAP_END", {
  24884. /**
  24885. * Mesh cap setting : one cap at the end of the mesh
  24886. */
  24887. get: function () {
  24888. return Mesh._CAP_END;
  24889. },
  24890. enumerable: true,
  24891. configurable: true
  24892. });
  24893. Object.defineProperty(Mesh, "CAP_ALL", {
  24894. /**
  24895. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  24896. */
  24897. get: function () {
  24898. return Mesh._CAP_ALL;
  24899. },
  24900. enumerable: true,
  24901. configurable: true
  24902. });
  24903. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  24904. set: function (callback) {
  24905. if (this._onBeforeDrawObserver) {
  24906. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  24907. }
  24908. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  24909. },
  24910. enumerable: true,
  24911. configurable: true
  24912. });
  24913. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  24914. get: function () {
  24915. return this._morphTargetManager;
  24916. },
  24917. set: function (value) {
  24918. if (this._morphTargetManager === value) {
  24919. return;
  24920. }
  24921. this._morphTargetManager = value;
  24922. this._syncGeometryWithMorphTargetManager();
  24923. },
  24924. enumerable: true,
  24925. configurable: true
  24926. });
  24927. Object.defineProperty(Mesh.prototype, "source", {
  24928. get: function () {
  24929. return this._source;
  24930. },
  24931. enumerable: true,
  24932. configurable: true
  24933. });
  24934. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  24935. get: function () {
  24936. return this._unIndexed;
  24937. },
  24938. set: function (value) {
  24939. if (this._unIndexed !== value) {
  24940. this._unIndexed = value;
  24941. this._markSubMeshesAsAttributesDirty();
  24942. }
  24943. },
  24944. enumerable: true,
  24945. configurable: true
  24946. });
  24947. // Methods
  24948. /**
  24949. * Returns the string "Mesh".
  24950. */
  24951. Mesh.prototype.getClassName = function () {
  24952. return "Mesh";
  24953. };
  24954. /**
  24955. * Returns a string.
  24956. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24957. */
  24958. Mesh.prototype.toString = function (fullDetails) {
  24959. var ret = _super.prototype.toString.call(this, fullDetails);
  24960. ret += ", n vertices: " + this.getTotalVertices();
  24961. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  24962. if (this.animations) {
  24963. for (var i = 0; i < this.animations.length; i++) {
  24964. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  24965. }
  24966. }
  24967. if (fullDetails) {
  24968. if (this._geometry) {
  24969. var ib = this.getIndices();
  24970. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24971. if (vb && ib) {
  24972. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  24973. }
  24974. }
  24975. else {
  24976. ret += ", flat shading: UNKNOWN";
  24977. }
  24978. }
  24979. return ret;
  24980. };
  24981. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  24982. /**
  24983. * True if the mesh has some Levels Of Details (LOD).
  24984. * Returns a boolean.
  24985. */
  24986. get: function () {
  24987. return this._LODLevels.length > 0;
  24988. },
  24989. enumerable: true,
  24990. configurable: true
  24991. });
  24992. Mesh.prototype._sortLODLevels = function () {
  24993. this._LODLevels.sort(function (a, b) {
  24994. if (a.distance < b.distance) {
  24995. return 1;
  24996. }
  24997. if (a.distance > b.distance) {
  24998. return -1;
  24999. }
  25000. return 0;
  25001. });
  25002. };
  25003. /**
  25004. * Add a mesh as LOD level triggered at the given distance.
  25005. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25006. * @param {number} distance The distance from the center of the object to show this level
  25007. * @param {Mesh} mesh The mesh to be added as LOD level
  25008. * @return {Mesh} This mesh (for chaining)
  25009. */
  25010. Mesh.prototype.addLODLevel = function (distance, mesh) {
  25011. if (mesh && mesh._masterMesh) {
  25012. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  25013. return this;
  25014. }
  25015. var level = new BABYLON.MeshLODLevel(distance, mesh);
  25016. this._LODLevels.push(level);
  25017. if (mesh) {
  25018. mesh._masterMesh = this;
  25019. }
  25020. this._sortLODLevels();
  25021. return this;
  25022. };
  25023. /**
  25024. * Returns the LOD level mesh at the passed distance or null if not found.
  25025. * It is related to the method `addLODLevel(distance, mesh)`.
  25026. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25027. * Returns an object Mesh or `null`.
  25028. */
  25029. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  25030. for (var index = 0; index < this._LODLevels.length; index++) {
  25031. var level = this._LODLevels[index];
  25032. if (level.distance === distance) {
  25033. return level.mesh;
  25034. }
  25035. }
  25036. return null;
  25037. };
  25038. /**
  25039. * Remove a mesh from the LOD array
  25040. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25041. * @param {Mesh} mesh The mesh to be removed.
  25042. * @return {Mesh} This mesh (for chaining)
  25043. */
  25044. Mesh.prototype.removeLODLevel = function (mesh) {
  25045. for (var index = 0; index < this._LODLevels.length; index++) {
  25046. if (this._LODLevels[index].mesh === mesh) {
  25047. this._LODLevels.splice(index, 1);
  25048. if (mesh) {
  25049. mesh._masterMesh = null;
  25050. }
  25051. }
  25052. }
  25053. this._sortLODLevels();
  25054. return this;
  25055. };
  25056. /**
  25057. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  25058. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25059. */
  25060. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  25061. if (!this._LODLevels || this._LODLevels.length === 0) {
  25062. return this;
  25063. }
  25064. var bSphere;
  25065. if (boundingSphere) {
  25066. bSphere = boundingSphere;
  25067. }
  25068. else {
  25069. var boundingInfo = this.getBoundingInfo();
  25070. bSphere = boundingInfo.boundingSphere;
  25071. }
  25072. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  25073. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  25074. if (this.onLODLevelSelection) {
  25075. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  25076. }
  25077. return this;
  25078. }
  25079. for (var index = 0; index < this._LODLevels.length; index++) {
  25080. var level = this._LODLevels[index];
  25081. if (level.distance < distanceToCamera) {
  25082. if (level.mesh) {
  25083. level.mesh._preActivate();
  25084. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  25085. }
  25086. if (this.onLODLevelSelection) {
  25087. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  25088. }
  25089. return level.mesh;
  25090. }
  25091. }
  25092. if (this.onLODLevelSelection) {
  25093. this.onLODLevelSelection(distanceToCamera, this, this);
  25094. }
  25095. return this;
  25096. };
  25097. Object.defineProperty(Mesh.prototype, "geometry", {
  25098. /**
  25099. * Returns the mesh internal Geometry object.
  25100. */
  25101. get: function () {
  25102. return this._geometry;
  25103. },
  25104. enumerable: true,
  25105. configurable: true
  25106. });
  25107. /**
  25108. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  25109. */
  25110. Mesh.prototype.getTotalVertices = function () {
  25111. if (this._geometry === null || this._geometry === undefined) {
  25112. return 0;
  25113. }
  25114. return this._geometry.getTotalVertices();
  25115. };
  25116. /**
  25117. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  25118. * 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.
  25119. * You can force the copy with forceCopy === true
  25120. * Returns null if the mesh has no geometry or no vertex buffer.
  25121. * Possible `kind` values :
  25122. * - BABYLON.VertexBuffer.PositionKind
  25123. * - BABYLON.VertexBuffer.UVKind
  25124. * - BABYLON.VertexBuffer.UV2Kind
  25125. * - BABYLON.VertexBuffer.UV3Kind
  25126. * - BABYLON.VertexBuffer.UV4Kind
  25127. * - BABYLON.VertexBuffer.UV5Kind
  25128. * - BABYLON.VertexBuffer.UV6Kind
  25129. * - BABYLON.VertexBuffer.ColorKind
  25130. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25131. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25132. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25133. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25134. */
  25135. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  25136. if (!this._geometry) {
  25137. return null;
  25138. }
  25139. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  25140. };
  25141. /**
  25142. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  25143. * Returns `null` if the mesh has no geometry.
  25144. * Possible `kind` values :
  25145. * - BABYLON.VertexBuffer.PositionKind
  25146. * - BABYLON.VertexBuffer.UVKind
  25147. * - BABYLON.VertexBuffer.UV2Kind
  25148. * - BABYLON.VertexBuffer.UV3Kind
  25149. * - BABYLON.VertexBuffer.UV4Kind
  25150. * - BABYLON.VertexBuffer.UV5Kind
  25151. * - BABYLON.VertexBuffer.UV6Kind
  25152. * - BABYLON.VertexBuffer.ColorKind
  25153. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25154. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25155. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25156. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25157. */
  25158. Mesh.prototype.getVertexBuffer = function (kind) {
  25159. if (!this._geometry) {
  25160. return null;
  25161. }
  25162. return this._geometry.getVertexBuffer(kind);
  25163. };
  25164. /**
  25165. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  25166. * Possible `kind` values :
  25167. * - BABYLON.VertexBuffer.PositionKind
  25168. * - BABYLON.VertexBuffer.UVKind
  25169. * - BABYLON.VertexBuffer.UV2Kind
  25170. * - BABYLON.VertexBuffer.UV3Kind
  25171. * - BABYLON.VertexBuffer.UV4Kind
  25172. * - BABYLON.VertexBuffer.UV5Kind
  25173. * - BABYLON.VertexBuffer.UV6Kind
  25174. * - BABYLON.VertexBuffer.ColorKind
  25175. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25176. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25177. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25178. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25179. */
  25180. Mesh.prototype.isVerticesDataPresent = function (kind) {
  25181. if (!this._geometry) {
  25182. if (this._delayInfo) {
  25183. return this._delayInfo.indexOf(kind) !== -1;
  25184. }
  25185. return false;
  25186. }
  25187. return this._geometry.isVerticesDataPresent(kind);
  25188. };
  25189. /**
  25190. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  25191. * Possible `kind` values :
  25192. * - BABYLON.VertexBuffer.PositionKind
  25193. * - BABYLON.VertexBuffer.UVKind
  25194. * - BABYLON.VertexBuffer.UV2Kind
  25195. * - BABYLON.VertexBuffer.UV3Kind
  25196. * - BABYLON.VertexBuffer.UV4Kind
  25197. * - BABYLON.VertexBuffer.UV5Kind
  25198. * - BABYLON.VertexBuffer.UV6Kind
  25199. * - BABYLON.VertexBuffer.ColorKind
  25200. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25201. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25202. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25203. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25204. */
  25205. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  25206. if (!this._geometry) {
  25207. if (this._delayInfo) {
  25208. return this._delayInfo.indexOf(kind) !== -1;
  25209. }
  25210. return false;
  25211. }
  25212. return this._geometry.isVertexBufferUpdatable(kind);
  25213. };
  25214. /**
  25215. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  25216. * Possible `kind` values :
  25217. * - BABYLON.VertexBuffer.PositionKind
  25218. * - BABYLON.VertexBuffer.UVKind
  25219. * - BABYLON.VertexBuffer.UV2Kind
  25220. * - BABYLON.VertexBuffer.UV3Kind
  25221. * - BABYLON.VertexBuffer.UV4Kind
  25222. * - BABYLON.VertexBuffer.UV5Kind
  25223. * - BABYLON.VertexBuffer.UV6Kind
  25224. * - BABYLON.VertexBuffer.ColorKind
  25225. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25226. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25227. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25228. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25229. */
  25230. Mesh.prototype.getVerticesDataKinds = function () {
  25231. if (!this._geometry) {
  25232. var result = new Array();
  25233. if (this._delayInfo) {
  25234. this._delayInfo.forEach(function (kind, index, array) {
  25235. result.push(kind);
  25236. });
  25237. }
  25238. return result;
  25239. }
  25240. return this._geometry.getVerticesDataKinds();
  25241. };
  25242. /**
  25243. * Returns a positive integer : the total number of indices in this mesh geometry.
  25244. * Returns zero if the mesh has no geometry.
  25245. */
  25246. Mesh.prototype.getTotalIndices = function () {
  25247. if (!this._geometry) {
  25248. return 0;
  25249. }
  25250. return this._geometry.getTotalIndices();
  25251. };
  25252. /**
  25253. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  25254. * 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.
  25255. * Returns an empty array if the mesh has no geometry.
  25256. */
  25257. Mesh.prototype.getIndices = function (copyWhenShared) {
  25258. if (!this._geometry) {
  25259. return [];
  25260. }
  25261. return this._geometry.getIndices(copyWhenShared);
  25262. };
  25263. Object.defineProperty(Mesh.prototype, "isBlocked", {
  25264. get: function () {
  25265. return this._masterMesh !== null && this._masterMesh !== undefined;
  25266. },
  25267. enumerable: true,
  25268. configurable: true
  25269. });
  25270. /**
  25271. * Determine if the current mesh is ready to be rendered
  25272. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  25273. * @returns true if all associated assets are ready (material, textures, shaders)
  25274. */
  25275. Mesh.prototype.isReady = function (forceInstanceSupport) {
  25276. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  25277. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25278. return false;
  25279. }
  25280. if (!_super.prototype.isReady.call(this)) {
  25281. return false;
  25282. }
  25283. if (!this.subMeshes || this.subMeshes.length === 0) {
  25284. return true;
  25285. }
  25286. var engine = this.getEngine();
  25287. var scene = this.getScene();
  25288. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  25289. this.computeWorldMatrix();
  25290. var mat = this.material || scene.defaultMaterial;
  25291. if (mat) {
  25292. if (mat.storeEffectOnSubMeshes) {
  25293. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25294. var subMesh = _a[_i];
  25295. var effectiveMaterial = subMesh.getMaterial();
  25296. if (effectiveMaterial) {
  25297. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25298. return false;
  25299. }
  25300. }
  25301. }
  25302. }
  25303. else {
  25304. if (!mat.isReady(this, hardwareInstancedRendering)) {
  25305. return false;
  25306. }
  25307. }
  25308. }
  25309. // Shadows
  25310. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  25311. var light = _c[_b];
  25312. var generator = light.getShadowGenerator();
  25313. if (generator) {
  25314. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  25315. var subMesh = _e[_d];
  25316. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  25317. return false;
  25318. }
  25319. }
  25320. }
  25321. }
  25322. // LOD
  25323. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  25324. var lod = _g[_f];
  25325. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  25326. return false;
  25327. }
  25328. }
  25329. return true;
  25330. };
  25331. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  25332. /**
  25333. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  25334. * This property is pertinent only for updatable parametric shapes.
  25335. */
  25336. get: function () {
  25337. return this._areNormalsFrozen;
  25338. },
  25339. enumerable: true,
  25340. configurable: true
  25341. });
  25342. /**
  25343. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25344. * It has no effect at all on other shapes.
  25345. * It prevents the mesh normals from being recomputed on next `positions` array update.
  25346. * Returns the Mesh.
  25347. */
  25348. Mesh.prototype.freezeNormals = function () {
  25349. this._areNormalsFrozen = true;
  25350. return this;
  25351. };
  25352. /**
  25353. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25354. * It has no effect at all on other shapes.
  25355. * It reactivates the mesh normals computation if it was previously frozen.
  25356. * Returns the Mesh.
  25357. */
  25358. Mesh.prototype.unfreezeNormals = function () {
  25359. this._areNormalsFrozen = false;
  25360. return this;
  25361. };
  25362. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  25363. /**
  25364. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  25365. */
  25366. set: function (count) {
  25367. this._overridenInstanceCount = count;
  25368. },
  25369. enumerable: true,
  25370. configurable: true
  25371. });
  25372. // Methods
  25373. Mesh.prototype._preActivate = function () {
  25374. var sceneRenderId = this.getScene().getRenderId();
  25375. if (this._preActivateId === sceneRenderId) {
  25376. return this;
  25377. }
  25378. this._preActivateId = sceneRenderId;
  25379. this._visibleInstances = null;
  25380. return this;
  25381. };
  25382. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  25383. if (this._visibleInstances) {
  25384. this._visibleInstances.intermediateDefaultRenderId = renderId;
  25385. }
  25386. return this;
  25387. };
  25388. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  25389. if (!this._visibleInstances) {
  25390. this._visibleInstances = {};
  25391. this._visibleInstances.defaultRenderId = renderId;
  25392. this._visibleInstances.selfDefaultRenderId = this._renderId;
  25393. }
  25394. if (!this._visibleInstances[renderId]) {
  25395. this._visibleInstances[renderId] = new Array();
  25396. }
  25397. this._visibleInstances[renderId].push(instance);
  25398. return this;
  25399. };
  25400. /**
  25401. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  25402. * This means the mesh underlying bounding box and sphere are recomputed.
  25403. * Returns the Mesh.
  25404. */
  25405. Mesh.prototype.refreshBoundingInfo = function () {
  25406. return this._refreshBoundingInfo(false);
  25407. };
  25408. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  25409. if (this._boundingInfo && this._boundingInfo.isLocked) {
  25410. return this;
  25411. }
  25412. var data = this._getPositionData(applySkeleton);
  25413. if (data) {
  25414. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  25415. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25416. }
  25417. if (this.subMeshes) {
  25418. for (var index = 0; index < this.subMeshes.length; index++) {
  25419. this.subMeshes[index].refreshBoundingInfo();
  25420. }
  25421. }
  25422. this._updateBoundingInfo();
  25423. return this;
  25424. };
  25425. Mesh.prototype._getPositionData = function (applySkeleton) {
  25426. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25427. if (data && applySkeleton && this.skeleton) {
  25428. data = data.slice();
  25429. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25430. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25431. if (matricesWeightsData && matricesIndicesData) {
  25432. var needExtras = this.numBoneInfluencers > 4;
  25433. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25434. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25435. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  25436. var tempVector = BABYLON.Tmp.Vector3[0];
  25437. var finalMatrix = BABYLON.Tmp.Matrix[0];
  25438. var tempMatrix = BABYLON.Tmp.Matrix[1];
  25439. var matWeightIdx = 0;
  25440. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  25441. finalMatrix.reset();
  25442. var inf;
  25443. var weight;
  25444. for (inf = 0; inf < 4; inf++) {
  25445. weight = matricesWeightsData[matWeightIdx + inf];
  25446. if (weight <= 0)
  25447. break;
  25448. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25449. finalMatrix.addToSelf(tempMatrix);
  25450. }
  25451. if (needExtras) {
  25452. for (inf = 0; inf < 4; inf++) {
  25453. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25454. if (weight <= 0)
  25455. break;
  25456. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25457. finalMatrix.addToSelf(tempMatrix);
  25458. }
  25459. }
  25460. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  25461. tempVector.toArray(data, index);
  25462. }
  25463. }
  25464. }
  25465. return data;
  25466. };
  25467. Mesh.prototype._createGlobalSubMesh = function (force) {
  25468. var totalVertices = this.getTotalVertices();
  25469. if (!totalVertices || !this.getIndices()) {
  25470. return null;
  25471. }
  25472. // Check if we need to recreate the submeshes
  25473. if (this.subMeshes && this.subMeshes.length > 0) {
  25474. var ib = this.getIndices();
  25475. if (!ib) {
  25476. return null;
  25477. }
  25478. var totalIndices = ib.length;
  25479. var needToRecreate = false;
  25480. if (force) {
  25481. needToRecreate = true;
  25482. }
  25483. else {
  25484. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25485. var submesh = _a[_i];
  25486. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  25487. needToRecreate = true;
  25488. break;
  25489. }
  25490. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  25491. needToRecreate = true;
  25492. break;
  25493. }
  25494. }
  25495. }
  25496. if (!needToRecreate) {
  25497. return this.subMeshes[0];
  25498. }
  25499. }
  25500. this.releaseSubMeshes();
  25501. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  25502. };
  25503. Mesh.prototype.subdivide = function (count) {
  25504. if (count < 1) {
  25505. return;
  25506. }
  25507. var totalIndices = this.getTotalIndices();
  25508. var subdivisionSize = (totalIndices / count) | 0;
  25509. var offset = 0;
  25510. // Ensure that subdivisionSize is a multiple of 3
  25511. while (subdivisionSize % 3 !== 0) {
  25512. subdivisionSize++;
  25513. }
  25514. this.releaseSubMeshes();
  25515. for (var index = 0; index < count; index++) {
  25516. if (offset >= totalIndices) {
  25517. break;
  25518. }
  25519. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  25520. offset += subdivisionSize;
  25521. }
  25522. this.synchronizeInstances();
  25523. };
  25524. /**
  25525. * Sets the vertex data of the mesh geometry for the requested `kind`.
  25526. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  25527. * The `data` are either a numeric array either a Float32Array.
  25528. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  25529. * 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).
  25530. * Note that a new underlying VertexBuffer object is created each call.
  25531. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  25532. *
  25533. * Possible `kind` values :
  25534. * - BABYLON.VertexBuffer.PositionKind
  25535. * - BABYLON.VertexBuffer.UVKind
  25536. * - BABYLON.VertexBuffer.UV2Kind
  25537. * - BABYLON.VertexBuffer.UV3Kind
  25538. * - BABYLON.VertexBuffer.UV4Kind
  25539. * - BABYLON.VertexBuffer.UV5Kind
  25540. * - BABYLON.VertexBuffer.UV6Kind
  25541. * - BABYLON.VertexBuffer.ColorKind
  25542. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25543. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25544. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25545. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25546. *
  25547. * Returns the Mesh.
  25548. */
  25549. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25550. if (updatable === void 0) { updatable = false; }
  25551. if (!this._geometry) {
  25552. var vertexData = new BABYLON.VertexData();
  25553. vertexData.set(data, kind);
  25554. var scene = this.getScene();
  25555. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25556. }
  25557. else {
  25558. this._geometry.setVerticesData(kind, data, updatable, stride);
  25559. }
  25560. return this;
  25561. };
  25562. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  25563. if (updatable === void 0) { updatable = true; }
  25564. var vb = this.getVertexBuffer(kind);
  25565. if (!vb || vb.isUpdatable() === updatable) {
  25566. return;
  25567. }
  25568. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  25569. };
  25570. /**
  25571. * Sets the mesh VertexBuffer.
  25572. * Returns the Mesh.
  25573. */
  25574. Mesh.prototype.setVerticesBuffer = function (buffer) {
  25575. if (!this._geometry) {
  25576. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  25577. }
  25578. this._geometry.setVerticesBuffer(buffer);
  25579. return this;
  25580. };
  25581. /**
  25582. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  25583. * If the mesh has no geometry, it is simply returned as it is.
  25584. * The `data` are either a numeric array either a Float32Array.
  25585. * No new underlying VertexBuffer object is created.
  25586. * 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.
  25587. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  25588. *
  25589. * Possible `kind` values :
  25590. * - BABYLON.VertexBuffer.PositionKind
  25591. * - BABYLON.VertexBuffer.UVKind
  25592. * - BABYLON.VertexBuffer.UV2Kind
  25593. * - BABYLON.VertexBuffer.UV3Kind
  25594. * - BABYLON.VertexBuffer.UV4Kind
  25595. * - BABYLON.VertexBuffer.UV5Kind
  25596. * - BABYLON.VertexBuffer.UV6Kind
  25597. * - BABYLON.VertexBuffer.ColorKind
  25598. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25599. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25600. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25601. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25602. *
  25603. * Returns the Mesh.
  25604. */
  25605. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  25606. if (!this._geometry) {
  25607. return this;
  25608. }
  25609. if (!makeItUnique) {
  25610. this._geometry.updateVerticesData(kind, data, updateExtends);
  25611. }
  25612. else {
  25613. this.makeGeometryUnique();
  25614. this.updateVerticesData(kind, data, updateExtends, false);
  25615. }
  25616. return this;
  25617. };
  25618. /**
  25619. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  25620. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  25621. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  25622. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  25623. * Returns the Mesh.
  25624. */
  25625. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  25626. if (computeNormals === void 0) { computeNormals = true; }
  25627. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25628. if (!positions) {
  25629. return this;
  25630. }
  25631. positionFunction(positions);
  25632. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25633. if (computeNormals) {
  25634. var indices = this.getIndices();
  25635. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25636. if (!normals) {
  25637. return this;
  25638. }
  25639. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  25640. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25641. }
  25642. return this;
  25643. };
  25644. /**
  25645. * Creates a un-shared specific occurence of the geometry for the mesh.
  25646. * Returns the Mesh.
  25647. */
  25648. Mesh.prototype.makeGeometryUnique = function () {
  25649. if (!this._geometry) {
  25650. return this;
  25651. }
  25652. var oldGeometry = this._geometry;
  25653. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  25654. oldGeometry.releaseForMesh(this, true);
  25655. geometry.applyToMesh(this);
  25656. return this;
  25657. };
  25658. /**
  25659. * Sets the mesh indices.
  25660. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  25661. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  25662. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  25663. * This method creates a new index buffer each call.
  25664. * Returns the Mesh.
  25665. */
  25666. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  25667. if (totalVertices === void 0) { totalVertices = null; }
  25668. if (updatable === void 0) { updatable = false; }
  25669. if (!this._geometry) {
  25670. var vertexData = new BABYLON.VertexData();
  25671. vertexData.indices = indices;
  25672. var scene = this.getScene();
  25673. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25674. }
  25675. else {
  25676. this._geometry.setIndices(indices, totalVertices, updatable);
  25677. }
  25678. return this;
  25679. };
  25680. /**
  25681. * Update the current index buffer
  25682. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  25683. * Returns the Mesh.
  25684. */
  25685. Mesh.prototype.updateIndices = function (indices, offset) {
  25686. if (!this._geometry) {
  25687. return this;
  25688. }
  25689. this._geometry.updateIndices(indices, offset);
  25690. return this;
  25691. };
  25692. /**
  25693. * Invert the geometry to move from a right handed system to a left handed one.
  25694. * Returns the Mesh.
  25695. */
  25696. Mesh.prototype.toLeftHanded = function () {
  25697. if (!this._geometry) {
  25698. return this;
  25699. }
  25700. this._geometry.toLeftHanded();
  25701. return this;
  25702. };
  25703. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  25704. if (!this._geometry) {
  25705. return this;
  25706. }
  25707. var engine = this.getScene().getEngine();
  25708. // Wireframe
  25709. var indexToBind;
  25710. if (this._unIndexed) {
  25711. indexToBind = null;
  25712. }
  25713. else {
  25714. switch (fillMode) {
  25715. case BABYLON.Material.PointFillMode:
  25716. indexToBind = null;
  25717. break;
  25718. case BABYLON.Material.WireFrameFillMode:
  25719. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  25720. break;
  25721. default:
  25722. case BABYLON.Material.TriangleFillMode:
  25723. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  25724. break;
  25725. }
  25726. }
  25727. // VBOs
  25728. this._geometry._bind(effect, indexToBind);
  25729. return this;
  25730. };
  25731. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  25732. if (alternate === void 0) { alternate = false; }
  25733. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25734. return this;
  25735. }
  25736. this.onBeforeDrawObservable.notifyObservers(this);
  25737. var scene = this.getScene();
  25738. var engine = scene.getEngine();
  25739. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  25740. // or triangles as points
  25741. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  25742. }
  25743. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  25744. // Triangles as wireframe
  25745. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  25746. }
  25747. else {
  25748. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  25749. }
  25750. if (scene._isAlternateRenderingEnabled && !alternate) {
  25751. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  25752. if (!effect || !scene.activeCamera) {
  25753. return this;
  25754. }
  25755. scene._switchToAlternateCameraConfiguration(true);
  25756. this._effectiveMaterial.bindView(effect);
  25757. this._effectiveMaterial.bindViewProjection(effect);
  25758. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  25759. this._draw(subMesh, fillMode, instancesCount, true);
  25760. engine.setViewport(scene.activeCamera.viewport);
  25761. scene._switchToAlternateCameraConfiguration(false);
  25762. this._effectiveMaterial.bindView(effect);
  25763. this._effectiveMaterial.bindViewProjection(effect);
  25764. }
  25765. return this;
  25766. };
  25767. /**
  25768. * Registers for this mesh a javascript function called just before the rendering process.
  25769. * This function is passed the current mesh.
  25770. * Return the Mesh.
  25771. */
  25772. Mesh.prototype.registerBeforeRender = function (func) {
  25773. this.onBeforeRenderObservable.add(func);
  25774. return this;
  25775. };
  25776. /**
  25777. * Disposes a previously registered javascript function called before the rendering.
  25778. * This function is passed the current mesh.
  25779. * Returns the Mesh.
  25780. */
  25781. Mesh.prototype.unregisterBeforeRender = function (func) {
  25782. this.onBeforeRenderObservable.removeCallback(func);
  25783. return this;
  25784. };
  25785. /**
  25786. * Registers for this mesh a javascript function called just after the rendering is complete.
  25787. * This function is passed the current mesh.
  25788. * Returns the Mesh.
  25789. */
  25790. Mesh.prototype.registerAfterRender = function (func) {
  25791. this.onAfterRenderObservable.add(func);
  25792. return this;
  25793. };
  25794. /**
  25795. * Disposes a previously registered javascript function called after the rendering.
  25796. * This function is passed the current mesh.
  25797. * Return the Mesh.
  25798. */
  25799. Mesh.prototype.unregisterAfterRender = function (func) {
  25800. this.onAfterRenderObservable.removeCallback(func);
  25801. return this;
  25802. };
  25803. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  25804. var scene = this.getScene();
  25805. this._batchCache.mustReturn = false;
  25806. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  25807. this._batchCache.visibleInstances[subMeshId] = null;
  25808. if (this._visibleInstances) {
  25809. var currentRenderId = scene.getRenderId();
  25810. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  25811. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  25812. var selfRenderId = this._renderId;
  25813. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  25814. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  25815. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  25816. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  25817. }
  25818. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  25819. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  25820. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  25821. this._batchCache.mustReturn = true;
  25822. return this._batchCache;
  25823. }
  25824. if (currentRenderId !== selfRenderId) {
  25825. this._batchCache.renderSelf[subMeshId] = false;
  25826. }
  25827. }
  25828. this._renderIdForInstances[subMeshId] = currentRenderId;
  25829. }
  25830. return this._batchCache;
  25831. };
  25832. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  25833. var visibleInstances = batch.visibleInstances[subMesh._id];
  25834. if (!visibleInstances) {
  25835. return this;
  25836. }
  25837. var matricesCount = visibleInstances.length + 1;
  25838. var bufferSize = matricesCount * 16 * 4;
  25839. var currentInstancesBufferSize = this._instancesBufferSize;
  25840. var instancesBuffer = this._instancesBuffer;
  25841. while (this._instancesBufferSize < bufferSize) {
  25842. this._instancesBufferSize *= 2;
  25843. }
  25844. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  25845. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  25846. }
  25847. var offset = 0;
  25848. var instancesCount = 0;
  25849. var world = this.getWorldMatrix();
  25850. if (batch.renderSelf[subMesh._id]) {
  25851. world.copyToArray(this._instancesData, offset);
  25852. offset += 16;
  25853. instancesCount++;
  25854. }
  25855. if (visibleInstances) {
  25856. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  25857. var instance = visibleInstances[instanceIndex];
  25858. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  25859. offset += 16;
  25860. instancesCount++;
  25861. }
  25862. }
  25863. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  25864. if (instancesBuffer) {
  25865. instancesBuffer.dispose();
  25866. }
  25867. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  25868. this._instancesBuffer = instancesBuffer;
  25869. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  25870. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  25871. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  25872. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  25873. }
  25874. else {
  25875. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  25876. }
  25877. this._bind(subMesh, effect, fillMode);
  25878. this._draw(subMesh, fillMode, instancesCount);
  25879. engine.unbindInstanceAttributes();
  25880. return this;
  25881. };
  25882. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  25883. var scene = this.getScene();
  25884. var engine = scene.getEngine();
  25885. if (hardwareInstancedRendering) {
  25886. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  25887. }
  25888. else {
  25889. if (batch.renderSelf[subMesh._id]) {
  25890. // Draw
  25891. if (onBeforeDraw) {
  25892. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  25893. }
  25894. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  25895. }
  25896. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  25897. if (visibleInstancesForSubMesh) {
  25898. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  25899. var instance = visibleInstancesForSubMesh[instanceIndex];
  25900. // World
  25901. var world = instance.getWorldMatrix();
  25902. if (onBeforeDraw) {
  25903. onBeforeDraw(true, world, effectiveMaterial);
  25904. }
  25905. // Draw
  25906. this._draw(subMesh, fillMode);
  25907. }
  25908. }
  25909. }
  25910. return this;
  25911. };
  25912. /**
  25913. * Triggers the draw call for the mesh.
  25914. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  25915. * Returns the Mesh.
  25916. */
  25917. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  25918. this.checkOcclusionQuery();
  25919. if (this._isOccluded) {
  25920. return this;
  25921. }
  25922. var scene = this.getScene();
  25923. // Managing instances
  25924. var batch = this._getInstancesRenderList(subMesh._id);
  25925. if (batch.mustReturn) {
  25926. return this;
  25927. }
  25928. // Checking geometry state
  25929. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25930. return this;
  25931. }
  25932. this.onBeforeRenderObservable.notifyObservers(this);
  25933. var engine = scene.getEngine();
  25934. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25935. // Material
  25936. var material = subMesh.getMaterial();
  25937. if (!material) {
  25938. return this;
  25939. }
  25940. this._effectiveMaterial = material;
  25941. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25942. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25943. return this;
  25944. }
  25945. }
  25946. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  25947. return this;
  25948. }
  25949. // Alpha mode
  25950. if (enableAlphaMode) {
  25951. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  25952. }
  25953. // Outline - step 1
  25954. var savedDepthWrite = engine.getDepthWrite();
  25955. if (this.renderOutline) {
  25956. engine.setDepthWrite(false);
  25957. scene.getOutlineRenderer().render(subMesh, batch);
  25958. engine.setDepthWrite(savedDepthWrite);
  25959. }
  25960. var effect;
  25961. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25962. effect = subMesh.effect;
  25963. }
  25964. else {
  25965. effect = this._effectiveMaterial.getEffect();
  25966. }
  25967. if (!effect) {
  25968. return this;
  25969. }
  25970. var sideOrientation = this.overrideMaterialSideOrientation;
  25971. if (sideOrientation == null) {
  25972. sideOrientation = this._effectiveMaterial.sideOrientation;
  25973. if (this._getWorldMatrixDeterminant() < 0) {
  25974. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  25975. }
  25976. }
  25977. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  25978. if (this._effectiveMaterial.forceDepthWrite) {
  25979. engine.setDepthWrite(true);
  25980. }
  25981. // Bind
  25982. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  25983. if (!hardwareInstancedRendering) {
  25984. this._bind(subMesh, effect, fillMode);
  25985. }
  25986. var world = this.getWorldMatrix();
  25987. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25988. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  25989. }
  25990. else {
  25991. this._effectiveMaterial.bind(world, this);
  25992. }
  25993. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  25994. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  25995. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25996. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  25997. }
  25998. // Draw
  25999. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26000. // Unbind
  26001. this._effectiveMaterial.unbind();
  26002. // Outline - step 2
  26003. if (this.renderOutline && savedDepthWrite) {
  26004. engine.setDepthWrite(true);
  26005. engine.setColorWrite(false);
  26006. scene.getOutlineRenderer().render(subMesh, batch);
  26007. engine.setColorWrite(true);
  26008. }
  26009. // Overlay
  26010. if (this.renderOverlay) {
  26011. var currentMode = engine.getAlphaMode();
  26012. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26013. scene.getOutlineRenderer().render(subMesh, batch, true);
  26014. engine.setAlphaMode(currentMode);
  26015. }
  26016. this.onAfterRenderObservable.notifyObservers(this);
  26017. return this;
  26018. };
  26019. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  26020. if (isInstance && effectiveMaterial) {
  26021. effectiveMaterial.bindOnlyWorldMatrix(world);
  26022. }
  26023. };
  26024. /**
  26025. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  26026. */
  26027. Mesh.prototype.getEmittedParticleSystems = function () {
  26028. var results = new Array();
  26029. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26030. var particleSystem = this.getScene().particleSystems[index];
  26031. if (particleSystem.emitter === this) {
  26032. results.push(particleSystem);
  26033. }
  26034. }
  26035. return results;
  26036. };
  26037. /**
  26038. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  26039. */
  26040. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  26041. var results = new Array();
  26042. var descendants = this.getDescendants();
  26043. descendants.push(this);
  26044. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26045. var particleSystem = this.getScene().particleSystems[index];
  26046. var emitter = particleSystem.emitter;
  26047. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  26048. results.push(particleSystem);
  26049. }
  26050. }
  26051. return results;
  26052. };
  26053. Mesh.prototype._checkDelayState = function () {
  26054. var scene = this.getScene();
  26055. if (this._geometry) {
  26056. this._geometry.load(scene);
  26057. }
  26058. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26059. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26060. this._queueLoad(scene);
  26061. }
  26062. return this;
  26063. };
  26064. Mesh.prototype._queueLoad = function (scene) {
  26065. var _this = this;
  26066. scene._addPendingData(this);
  26067. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  26068. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26069. if (data instanceof ArrayBuffer) {
  26070. _this._delayLoadingFunction(data, _this);
  26071. }
  26072. else {
  26073. _this._delayLoadingFunction(JSON.parse(data), _this);
  26074. }
  26075. _this.instances.forEach(function (instance) {
  26076. instance._syncSubMeshes();
  26077. });
  26078. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26079. scene._removePendingData(_this);
  26080. }, function () { }, scene.database, getBinaryData);
  26081. return this;
  26082. };
  26083. /**
  26084. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  26085. */
  26086. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  26087. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26088. return false;
  26089. }
  26090. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  26091. return false;
  26092. }
  26093. this._checkDelayState();
  26094. return true;
  26095. };
  26096. /**
  26097. * Sets the mesh material by the material or multiMaterial `id` property.
  26098. * The material `id` is a string identifying the material or the multiMaterial.
  26099. * This method returns the Mesh.
  26100. */
  26101. Mesh.prototype.setMaterialByID = function (id) {
  26102. var materials = this.getScene().materials;
  26103. var index;
  26104. for (index = materials.length - 1; index > -1; index--) {
  26105. if (materials[index].id === id) {
  26106. this.material = materials[index];
  26107. return this;
  26108. }
  26109. }
  26110. // Multi
  26111. var multiMaterials = this.getScene().multiMaterials;
  26112. for (index = multiMaterials.length - 1; index > -1; index--) {
  26113. if (multiMaterials[index].id === id) {
  26114. this.material = multiMaterials[index];
  26115. return this;
  26116. }
  26117. }
  26118. return this;
  26119. };
  26120. /**
  26121. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  26122. */
  26123. Mesh.prototype.getAnimatables = function () {
  26124. var results = new Array();
  26125. if (this.material) {
  26126. results.push(this.material);
  26127. }
  26128. if (this.skeleton) {
  26129. results.push(this.skeleton);
  26130. }
  26131. return results;
  26132. };
  26133. /**
  26134. * Modifies the mesh geometry according to the passed transformation matrix.
  26135. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  26136. * The mesh normals are modified accordingly the same transformation.
  26137. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  26138. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26139. * Returns the Mesh.
  26140. */
  26141. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  26142. // Position
  26143. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26144. return this;
  26145. }
  26146. var submeshes = this.subMeshes.splice(0);
  26147. this._resetPointsArrayCache();
  26148. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26149. var temp = new Array();
  26150. var index;
  26151. for (index = 0; index < data.length; index += 3) {
  26152. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  26153. }
  26154. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  26155. // Normals
  26156. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26157. return this;
  26158. }
  26159. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26160. temp = [];
  26161. for (index = 0; index < data.length; index += 3) {
  26162. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  26163. }
  26164. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  26165. // flip faces?
  26166. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  26167. this.flipFaces();
  26168. }
  26169. // Restore submeshes
  26170. this.releaseSubMeshes();
  26171. this.subMeshes = submeshes;
  26172. return this;
  26173. };
  26174. /**
  26175. * Modifies the mesh geometry according to its own current World Matrix.
  26176. * The mesh World Matrix is then reset.
  26177. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  26178. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  26179. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26180. * Returns the Mesh.
  26181. */
  26182. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  26183. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  26184. this.scaling.copyFromFloats(1, 1, 1);
  26185. this.position.copyFromFloats(0, 0, 0);
  26186. this.rotation.copyFromFloats(0, 0, 0);
  26187. //only if quaternion is already set
  26188. if (this.rotationQuaternion) {
  26189. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  26190. }
  26191. this._worldMatrix = BABYLON.Matrix.Identity();
  26192. return this;
  26193. };
  26194. Object.defineProperty(Mesh.prototype, "_positions", {
  26195. // Cache
  26196. get: function () {
  26197. if (this._geometry) {
  26198. return this._geometry._positions;
  26199. }
  26200. return null;
  26201. },
  26202. enumerable: true,
  26203. configurable: true
  26204. });
  26205. Mesh.prototype._resetPointsArrayCache = function () {
  26206. if (this._geometry) {
  26207. this._geometry._resetPointsArrayCache();
  26208. }
  26209. return this;
  26210. };
  26211. Mesh.prototype._generatePointsArray = function () {
  26212. if (this._geometry) {
  26213. return this._geometry._generatePointsArray();
  26214. }
  26215. return false;
  26216. };
  26217. /**
  26218. * Returns a new Mesh object generated from the current mesh properties.
  26219. * This method must not get confused with createInstance().
  26220. * The parameter `name` is a string, the name given to the new mesh.
  26221. * The optional parameter `newParent` can be any Node object (default `null`).
  26222. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  26223. * 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.
  26224. */
  26225. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  26226. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26227. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  26228. };
  26229. /**
  26230. * Disposes the Mesh.
  26231. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  26232. * Returns nothing.
  26233. */
  26234. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  26235. var _this = this;
  26236. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  26237. this.morphTargetManager = null;
  26238. if (this._geometry) {
  26239. this._geometry.releaseForMesh(this, true);
  26240. }
  26241. // Sources
  26242. var meshes = this.getScene().meshes;
  26243. meshes.forEach(function (abstractMesh) {
  26244. var mesh = abstractMesh;
  26245. if (mesh._source && mesh._source === _this) {
  26246. mesh._source = null;
  26247. }
  26248. });
  26249. this._source = null;
  26250. // Instances
  26251. if (this._instancesBuffer) {
  26252. this._instancesBuffer.dispose();
  26253. this._instancesBuffer = null;
  26254. }
  26255. while (this.instances.length) {
  26256. this.instances[0].dispose();
  26257. }
  26258. // Highlight layers.
  26259. var highlightLayers = this.getScene().highlightLayers;
  26260. for (var i = 0; i < highlightLayers.length; i++) {
  26261. var highlightLayer = highlightLayers[i];
  26262. if (highlightLayer) {
  26263. highlightLayer.removeMesh(this);
  26264. highlightLayer.removeExcludedMesh(this);
  26265. }
  26266. }
  26267. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  26268. };
  26269. /**
  26270. * Modifies the mesh geometry according to a displacement map.
  26271. * 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.
  26272. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26273. * This method returns nothing.
  26274. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  26275. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26276. * 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.
  26277. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26278. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26279. *
  26280. * Returns the Mesh.
  26281. */
  26282. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  26283. var _this = this;
  26284. var scene = this.getScene();
  26285. var onload = function (img) {
  26286. // Getting height map data
  26287. var canvas = document.createElement("canvas");
  26288. var context = canvas.getContext("2d");
  26289. var heightMapWidth = img.width;
  26290. var heightMapHeight = img.height;
  26291. canvas.width = heightMapWidth;
  26292. canvas.height = heightMapHeight;
  26293. context.drawImage(img, 0, 0);
  26294. // Create VertexData from map data
  26295. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26296. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  26297. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  26298. //execute success callback, if set
  26299. if (onSuccess) {
  26300. onSuccess(_this);
  26301. }
  26302. };
  26303. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26304. return this;
  26305. };
  26306. /**
  26307. * Modifies the mesh geometry according to a displacementMap buffer.
  26308. * 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.
  26309. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26310. * This method returns nothing.
  26311. * 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.
  26312. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  26313. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26314. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26315. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26316. *
  26317. * Returns the Mesh.
  26318. */
  26319. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  26320. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  26321. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  26322. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26323. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  26324. return this;
  26325. }
  26326. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26327. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26328. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26329. var position = BABYLON.Vector3.Zero();
  26330. var normal = BABYLON.Vector3.Zero();
  26331. var uv = BABYLON.Vector2.Zero();
  26332. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  26333. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  26334. for (var index = 0; index < positions.length; index += 3) {
  26335. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  26336. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  26337. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  26338. // Compute height
  26339. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  26340. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  26341. var pos = (u + v * heightMapWidth) * 4;
  26342. var r = buffer[pos] / 255.0;
  26343. var g = buffer[pos + 1] / 255.0;
  26344. var b = buffer[pos + 2] / 255.0;
  26345. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26346. normal.normalize();
  26347. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  26348. position = position.add(normal);
  26349. position.toArray(positions, index);
  26350. }
  26351. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  26352. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  26353. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  26354. return this;
  26355. };
  26356. /**
  26357. * Modify the mesh to get a flat shading rendering.
  26358. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  26359. * This method returns the Mesh.
  26360. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  26361. */
  26362. Mesh.prototype.convertToFlatShadedMesh = function () {
  26363. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  26364. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26365. var kinds = this.getVerticesDataKinds();
  26366. var vbs = {};
  26367. var data = {};
  26368. var newdata = {};
  26369. var updatableNormals = false;
  26370. var kindIndex;
  26371. var kind;
  26372. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26373. kind = kinds[kindIndex];
  26374. var vertexBuffer = this.getVertexBuffer(kind);
  26375. if (kind === BABYLON.VertexBuffer.NormalKind) {
  26376. updatableNormals = vertexBuffer.isUpdatable();
  26377. kinds.splice(kindIndex, 1);
  26378. kindIndex--;
  26379. continue;
  26380. }
  26381. vbs[kind] = vertexBuffer;
  26382. data[kind] = vbs[kind].getData();
  26383. newdata[kind] = [];
  26384. }
  26385. // Save previous submeshes
  26386. var previousSubmeshes = this.subMeshes.slice(0);
  26387. var indices = this.getIndices();
  26388. var totalIndices = this.getTotalIndices();
  26389. // Generating unique vertices per face
  26390. var index;
  26391. for (index = 0; index < totalIndices; index++) {
  26392. var vertexIndex = indices[index];
  26393. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26394. kind = kinds[kindIndex];
  26395. var stride = vbs[kind].getStrideSize();
  26396. for (var offset = 0; offset < stride; offset++) {
  26397. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26398. }
  26399. }
  26400. }
  26401. // Updating faces & normal
  26402. var normals = [];
  26403. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  26404. for (index = 0; index < totalIndices; index += 3) {
  26405. indices[index] = index;
  26406. indices[index + 1] = index + 1;
  26407. indices[index + 2] = index + 2;
  26408. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  26409. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  26410. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  26411. var p1p2 = p1.subtract(p2);
  26412. var p3p2 = p3.subtract(p2);
  26413. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  26414. // Store same normals for every vertex
  26415. for (var localIndex = 0; localIndex < 3; localIndex++) {
  26416. normals.push(normal.x);
  26417. normals.push(normal.y);
  26418. normals.push(normal.z);
  26419. }
  26420. }
  26421. this.setIndices(indices);
  26422. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  26423. // Updating vertex buffers
  26424. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26425. kind = kinds[kindIndex];
  26426. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26427. }
  26428. // Updating submeshes
  26429. this.releaseSubMeshes();
  26430. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26431. var previousOne = previousSubmeshes[submeshIndex];
  26432. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26433. }
  26434. this.synchronizeInstances();
  26435. return this;
  26436. };
  26437. /**
  26438. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  26439. * In other words, more vertices, no more indices and a single bigger VBO.
  26440. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  26441. * Returns the Mesh.
  26442. */
  26443. Mesh.prototype.convertToUnIndexedMesh = function () {
  26444. /// <summary>Remove indices by unfolding faces into buffers</summary>
  26445. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26446. var kinds = this.getVerticesDataKinds();
  26447. var vbs = {};
  26448. var data = {};
  26449. var newdata = {};
  26450. var kindIndex;
  26451. var kind;
  26452. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26453. kind = kinds[kindIndex];
  26454. var vertexBuffer = this.getVertexBuffer(kind);
  26455. vbs[kind] = vertexBuffer;
  26456. data[kind] = vbs[kind].getData();
  26457. newdata[kind] = [];
  26458. }
  26459. // Save previous submeshes
  26460. var previousSubmeshes = this.subMeshes.slice(0);
  26461. var indices = this.getIndices();
  26462. var totalIndices = this.getTotalIndices();
  26463. // Generating unique vertices per face
  26464. var index;
  26465. for (index = 0; index < totalIndices; index++) {
  26466. var vertexIndex = indices[index];
  26467. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26468. kind = kinds[kindIndex];
  26469. var stride = vbs[kind].getStrideSize();
  26470. for (var offset = 0; offset < stride; offset++) {
  26471. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26472. }
  26473. }
  26474. }
  26475. // Updating indices
  26476. for (index = 0; index < totalIndices; index += 3) {
  26477. indices[index] = index;
  26478. indices[index + 1] = index + 1;
  26479. indices[index + 2] = index + 2;
  26480. }
  26481. this.setIndices(indices);
  26482. // Updating vertex buffers
  26483. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26484. kind = kinds[kindIndex];
  26485. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26486. }
  26487. // Updating submeshes
  26488. this.releaseSubMeshes();
  26489. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26490. var previousOne = previousSubmeshes[submeshIndex];
  26491. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26492. }
  26493. this._unIndexed = true;
  26494. this.synchronizeInstances();
  26495. return this;
  26496. };
  26497. /**
  26498. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  26499. * This method returns the Mesh.
  26500. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  26501. */
  26502. Mesh.prototype.flipFaces = function (flipNormals) {
  26503. if (flipNormals === void 0) { flipNormals = false; }
  26504. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  26505. var i;
  26506. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  26507. for (i = 0; i < vertex_data.normals.length; i++) {
  26508. vertex_data.normals[i] *= -1;
  26509. }
  26510. }
  26511. if (vertex_data.indices) {
  26512. var temp;
  26513. for (i = 0; i < vertex_data.indices.length; i += 3) {
  26514. // reassign indices
  26515. temp = vertex_data.indices[i + 1];
  26516. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  26517. vertex_data.indices[i + 2] = temp;
  26518. }
  26519. }
  26520. vertex_data.applyToMesh(this);
  26521. return this;
  26522. };
  26523. // Instances
  26524. /**
  26525. * Creates a new InstancedMesh object from the mesh model.
  26526. * An instance shares the same properties and the same material than its model.
  26527. * Only these properties of each instance can then be set individually :
  26528. * - position
  26529. * - rotation
  26530. * - rotationQuaternion
  26531. * - setPivotMatrix
  26532. * - scaling
  26533. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  26534. * Warning : this method is not supported for Line mesh and LineSystem
  26535. */
  26536. Mesh.prototype.createInstance = function (name) {
  26537. return new BABYLON.InstancedMesh(name, this);
  26538. };
  26539. /**
  26540. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  26541. * After this call, all the mesh instances have the same submeshes than the current mesh.
  26542. * This method returns the Mesh.
  26543. */
  26544. Mesh.prototype.synchronizeInstances = function () {
  26545. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  26546. var instance = this.instances[instanceIndex];
  26547. instance._syncSubMeshes();
  26548. }
  26549. return this;
  26550. };
  26551. /**
  26552. * Simplify the mesh according to the given array of settings.
  26553. * Function will return immediately and will simplify async. It returns the Mesh.
  26554. * @param settings a collection of simplification settings.
  26555. * @param parallelProcessing should all levels calculate parallel or one after the other.
  26556. * @param type the type of simplification to run.
  26557. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  26558. */
  26559. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  26560. if (parallelProcessing === void 0) { parallelProcessing = true; }
  26561. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  26562. this.getScene().simplificationQueue.addTask({
  26563. settings: settings,
  26564. parallelProcessing: parallelProcessing,
  26565. mesh: this,
  26566. simplificationType: simplificationType,
  26567. successCallback: successCallback
  26568. });
  26569. return this;
  26570. };
  26571. /**
  26572. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  26573. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  26574. * This should be used together with the simplification to avoid disappearing triangles.
  26575. * Returns the Mesh.
  26576. * @param successCallback an optional success callback to be called after the optimization finished.
  26577. */
  26578. Mesh.prototype.optimizeIndices = function (successCallback) {
  26579. var _this = this;
  26580. var indices = this.getIndices();
  26581. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26582. if (!positions || !indices) {
  26583. return this;
  26584. }
  26585. var vectorPositions = new Array();
  26586. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  26587. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  26588. }
  26589. var dupes = new Array();
  26590. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  26591. var realPos = vectorPositions.length - 1 - iteration;
  26592. var testedPosition = vectorPositions[realPos];
  26593. for (var j = 0; j < realPos; ++j) {
  26594. var againstPosition = vectorPositions[j];
  26595. if (testedPosition.equals(againstPosition)) {
  26596. dupes[realPos] = j;
  26597. break;
  26598. }
  26599. }
  26600. }, function () {
  26601. for (var i = 0; i < indices.length; ++i) {
  26602. indices[i] = dupes[indices[i]] || indices[i];
  26603. }
  26604. //indices are now reordered
  26605. var originalSubMeshes = _this.subMeshes.slice(0);
  26606. _this.setIndices(indices);
  26607. _this.subMeshes = originalSubMeshes;
  26608. if (successCallback) {
  26609. successCallback(_this);
  26610. }
  26611. });
  26612. return this;
  26613. };
  26614. Mesh.prototype.serialize = function (serializationObject) {
  26615. serializationObject.name = this.name;
  26616. serializationObject.id = this.id;
  26617. serializationObject.type = this.getClassName();
  26618. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  26619. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26620. }
  26621. serializationObject.position = this.position.asArray();
  26622. if (this.rotationQuaternion) {
  26623. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  26624. }
  26625. else if (this.rotation) {
  26626. serializationObject.rotation = this.rotation.asArray();
  26627. }
  26628. serializationObject.scaling = this.scaling.asArray();
  26629. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  26630. serializationObject.isEnabled = this.isEnabled(false);
  26631. serializationObject.isVisible = this.isVisible;
  26632. serializationObject.infiniteDistance = this.infiniteDistance;
  26633. serializationObject.pickable = this.isPickable;
  26634. serializationObject.receiveShadows = this.receiveShadows;
  26635. serializationObject.billboardMode = this.billboardMode;
  26636. serializationObject.visibility = this.visibility;
  26637. serializationObject.checkCollisions = this.checkCollisions;
  26638. serializationObject.isBlocker = this.isBlocker;
  26639. // Parent
  26640. if (this.parent) {
  26641. serializationObject.parentId = this.parent.id;
  26642. }
  26643. // Geometry
  26644. serializationObject.isUnIndexed = this.isUnIndexed;
  26645. var geometry = this._geometry;
  26646. if (geometry) {
  26647. var geometryId = geometry.id;
  26648. serializationObject.geometryId = geometryId;
  26649. // SubMeshes
  26650. serializationObject.subMeshes = [];
  26651. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  26652. var subMesh = this.subMeshes[subIndex];
  26653. serializationObject.subMeshes.push({
  26654. materialIndex: subMesh.materialIndex,
  26655. verticesStart: subMesh.verticesStart,
  26656. verticesCount: subMesh.verticesCount,
  26657. indexStart: subMesh.indexStart,
  26658. indexCount: subMesh.indexCount
  26659. });
  26660. }
  26661. }
  26662. // Material
  26663. if (this.material) {
  26664. serializationObject.materialId = this.material.id;
  26665. }
  26666. else {
  26667. this.material = null;
  26668. }
  26669. // Morph targets
  26670. if (this.morphTargetManager) {
  26671. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  26672. }
  26673. // Skeleton
  26674. if (this.skeleton) {
  26675. serializationObject.skeletonId = this.skeleton.id;
  26676. }
  26677. // Physics
  26678. //TODO implement correct serialization for physics impostors.
  26679. var impostor = this.getPhysicsImpostor();
  26680. if (impostor) {
  26681. serializationObject.physicsMass = impostor.getParam("mass");
  26682. serializationObject.physicsFriction = impostor.getParam("friction");
  26683. serializationObject.physicsRestitution = impostor.getParam("mass");
  26684. serializationObject.physicsImpostor = impostor.type;
  26685. }
  26686. // Metadata
  26687. if (this.metadata) {
  26688. serializationObject.metadata = this.metadata;
  26689. }
  26690. // Instances
  26691. serializationObject.instances = [];
  26692. for (var index = 0; index < this.instances.length; index++) {
  26693. var instance = this.instances[index];
  26694. var serializationInstance = {
  26695. name: instance.name,
  26696. id: instance.id,
  26697. position: instance.position.asArray(),
  26698. scaling: instance.scaling.asArray()
  26699. };
  26700. if (instance.rotationQuaternion) {
  26701. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  26702. }
  26703. else if (instance.rotation) {
  26704. serializationInstance.rotation = instance.rotation.asArray();
  26705. }
  26706. serializationObject.instances.push(serializationInstance);
  26707. // Animations
  26708. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  26709. serializationInstance.ranges = instance.serializeAnimationRanges();
  26710. }
  26711. //
  26712. // Animations
  26713. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26714. serializationObject.ranges = this.serializeAnimationRanges();
  26715. // Layer mask
  26716. serializationObject.layerMask = this.layerMask;
  26717. // Alpha
  26718. serializationObject.alphaIndex = this.alphaIndex;
  26719. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  26720. // Overlay
  26721. serializationObject.overlayAlpha = this.overlayAlpha;
  26722. serializationObject.overlayColor = this.overlayColor.asArray();
  26723. serializationObject.renderOverlay = this.renderOverlay;
  26724. // Fog
  26725. serializationObject.applyFog = this.applyFog;
  26726. // Action Manager
  26727. if (this.actionManager) {
  26728. serializationObject.actions = this.actionManager.serialize(this.name);
  26729. }
  26730. };
  26731. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  26732. if (!this.geometry) {
  26733. return;
  26734. }
  26735. this._markSubMeshesAsAttributesDirty();
  26736. var morphTargetManager = this._morphTargetManager;
  26737. if (morphTargetManager && morphTargetManager.vertexCount) {
  26738. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  26739. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  26740. this.morphTargetManager = null;
  26741. return;
  26742. }
  26743. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  26744. var morphTarget = morphTargetManager.getActiveTarget(index);
  26745. var positions = morphTarget.getPositions();
  26746. if (!positions) {
  26747. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  26748. return;
  26749. }
  26750. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  26751. var normals = morphTarget.getNormals();
  26752. if (normals) {
  26753. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  26754. }
  26755. var tangents = morphTarget.getTangents();
  26756. if (tangents) {
  26757. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  26758. }
  26759. }
  26760. }
  26761. else {
  26762. var index = 0;
  26763. // Positions
  26764. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  26765. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  26766. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  26767. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  26768. }
  26769. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  26770. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  26771. }
  26772. index++;
  26773. }
  26774. }
  26775. };
  26776. // Statics
  26777. /**
  26778. * Returns a new Mesh object parsed from the source provided.
  26779. * The parameter `parsedMesh` is the source.
  26780. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  26781. */
  26782. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  26783. var mesh;
  26784. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  26785. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  26786. }
  26787. else {
  26788. mesh = new Mesh(parsedMesh.name, scene);
  26789. }
  26790. mesh.id = parsedMesh.id;
  26791. if (BABYLON.Tags) {
  26792. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  26793. }
  26794. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  26795. if (parsedMesh.metadata !== undefined) {
  26796. mesh.metadata = parsedMesh.metadata;
  26797. }
  26798. if (parsedMesh.rotationQuaternion) {
  26799. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  26800. }
  26801. else if (parsedMesh.rotation) {
  26802. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  26803. }
  26804. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  26805. if (parsedMesh.localMatrix) {
  26806. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  26807. }
  26808. else if (parsedMesh.pivotMatrix) {
  26809. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  26810. }
  26811. mesh.setEnabled(parsedMesh.isEnabled);
  26812. mesh.isVisible = parsedMesh.isVisible;
  26813. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  26814. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  26815. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  26816. if (parsedMesh.applyFog !== undefined) {
  26817. mesh.applyFog = parsedMesh.applyFog;
  26818. }
  26819. if (parsedMesh.pickable !== undefined) {
  26820. mesh.isPickable = parsedMesh.pickable;
  26821. }
  26822. if (parsedMesh.alphaIndex !== undefined) {
  26823. mesh.alphaIndex = parsedMesh.alphaIndex;
  26824. }
  26825. mesh.receiveShadows = parsedMesh.receiveShadows;
  26826. mesh.billboardMode = parsedMesh.billboardMode;
  26827. if (parsedMesh.visibility !== undefined) {
  26828. mesh.visibility = parsedMesh.visibility;
  26829. }
  26830. mesh.checkCollisions = parsedMesh.checkCollisions;
  26831. if (parsedMesh.isBlocker !== undefined) {
  26832. mesh.isBlocker = parsedMesh.isBlocker;
  26833. }
  26834. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  26835. // freezeWorldMatrix
  26836. if (parsedMesh.freezeWorldMatrix) {
  26837. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  26838. }
  26839. // Parent
  26840. if (parsedMesh.parentId) {
  26841. mesh._waitingParentId = parsedMesh.parentId;
  26842. }
  26843. // Actions
  26844. if (parsedMesh.actions !== undefined) {
  26845. mesh._waitingActions = parsedMesh.actions;
  26846. }
  26847. // Overlay
  26848. if (parsedMesh.overlayAlpha !== undefined) {
  26849. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  26850. }
  26851. if (parsedMesh.overlayColor !== undefined) {
  26852. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  26853. }
  26854. if (parsedMesh.renderOverlay !== undefined) {
  26855. mesh.renderOverlay = parsedMesh.renderOverlay;
  26856. }
  26857. // Geometry
  26858. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  26859. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  26860. if (parsedMesh.delayLoadingFile) {
  26861. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26862. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  26863. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  26864. if (parsedMesh._binaryInfo) {
  26865. mesh._binaryInfo = parsedMesh._binaryInfo;
  26866. }
  26867. mesh._delayInfo = [];
  26868. if (parsedMesh.hasUVs) {
  26869. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26870. }
  26871. if (parsedMesh.hasUVs2) {
  26872. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26873. }
  26874. if (parsedMesh.hasUVs3) {
  26875. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26876. }
  26877. if (parsedMesh.hasUVs4) {
  26878. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26879. }
  26880. if (parsedMesh.hasUVs5) {
  26881. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26882. }
  26883. if (parsedMesh.hasUVs6) {
  26884. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26885. }
  26886. if (parsedMesh.hasColors) {
  26887. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26888. }
  26889. if (parsedMesh.hasMatricesIndices) {
  26890. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26891. }
  26892. if (parsedMesh.hasMatricesWeights) {
  26893. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26894. }
  26895. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  26896. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  26897. mesh._checkDelayState();
  26898. }
  26899. }
  26900. else {
  26901. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  26902. }
  26903. // Material
  26904. if (parsedMesh.materialId) {
  26905. mesh.setMaterialByID(parsedMesh.materialId);
  26906. }
  26907. else {
  26908. mesh.material = null;
  26909. }
  26910. // Morph targets
  26911. if (parsedMesh.morphTargetManagerId > -1) {
  26912. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  26913. }
  26914. // Skeleton
  26915. if (parsedMesh.skeletonId > -1) {
  26916. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  26917. if (parsedMesh.numBoneInfluencers) {
  26918. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  26919. }
  26920. }
  26921. // Animations
  26922. if (parsedMesh.animations) {
  26923. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26924. var parsedAnimation = parsedMesh.animations[animationIndex];
  26925. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26926. }
  26927. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  26928. }
  26929. if (parsedMesh.autoAnimate) {
  26930. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  26931. }
  26932. // Layer Mask
  26933. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  26934. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  26935. }
  26936. else {
  26937. mesh.layerMask = 0x0FFFFFFF;
  26938. }
  26939. // Physics
  26940. if (parsedMesh.physicsImpostor) {
  26941. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  26942. mass: parsedMesh.physicsMass,
  26943. friction: parsedMesh.physicsFriction,
  26944. restitution: parsedMesh.physicsRestitution
  26945. }, scene);
  26946. }
  26947. // Instances
  26948. if (parsedMesh.instances) {
  26949. for (var index = 0; index < parsedMesh.instances.length; index++) {
  26950. var parsedInstance = parsedMesh.instances[index];
  26951. var instance = mesh.createInstance(parsedInstance.name);
  26952. if (parsedInstance.id) {
  26953. instance.id = parsedInstance.id;
  26954. }
  26955. if (BABYLON.Tags) {
  26956. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  26957. }
  26958. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  26959. if (parsedInstance.parentId) {
  26960. instance._waitingParentId = parsedInstance.parentId;
  26961. }
  26962. if (parsedInstance.rotationQuaternion) {
  26963. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  26964. }
  26965. else if (parsedInstance.rotation) {
  26966. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  26967. }
  26968. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  26969. instance.checkCollisions = mesh.checkCollisions;
  26970. if (parsedMesh.animations) {
  26971. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26972. parsedAnimation = parsedMesh.animations[animationIndex];
  26973. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26974. }
  26975. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  26976. }
  26977. }
  26978. }
  26979. return mesh;
  26980. };
  26981. /**
  26982. * Creates a ribbon mesh.
  26983. * Please consider using the same method from the MeshBuilder class instead.
  26984. * 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.
  26985. *
  26986. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  26987. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  26988. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  26989. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  26990. * 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.
  26991. * 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.
  26992. * 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
  26993. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26994. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26996. */
  26997. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  26998. if (closeArray === void 0) { closeArray = false; }
  26999. if (updatable === void 0) { updatable = false; }
  27000. return BABYLON.MeshBuilder.CreateRibbon(name, {
  27001. pathArray: pathArray,
  27002. closeArray: closeArray,
  27003. closePath: closePath,
  27004. offset: offset,
  27005. updatable: updatable,
  27006. sideOrientation: sideOrientation,
  27007. instance: instance
  27008. }, scene);
  27009. };
  27010. /**
  27011. * Creates a plane polygonal mesh. By default, this is a disc.
  27012. * Please consider using the same method from the MeshBuilder class instead.
  27013. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  27014. * 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.
  27015. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27016. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27017. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27018. */
  27019. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  27020. if (scene === void 0) { scene = null; }
  27021. var options = {
  27022. radius: radius,
  27023. tessellation: tessellation,
  27024. sideOrientation: sideOrientation,
  27025. updatable: updatable
  27026. };
  27027. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  27028. };
  27029. /**
  27030. * Creates a box mesh.
  27031. * Please consider using the same method from the MeshBuilder class instead.
  27032. * The parameter `size` sets the size (float) of each box side (default 1).
  27033. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27034. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27035. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27036. */
  27037. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  27038. if (scene === void 0) { scene = null; }
  27039. var options = {
  27040. size: size,
  27041. sideOrientation: sideOrientation,
  27042. updatable: updatable
  27043. };
  27044. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  27045. };
  27046. /**
  27047. * Creates a sphere mesh.
  27048. * Please consider using the same method from the MeshBuilder class instead.
  27049. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  27050. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  27051. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27052. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27053. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27054. */
  27055. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  27056. var options = {
  27057. segments: segments,
  27058. diameterX: diameter,
  27059. diameterY: diameter,
  27060. diameterZ: diameter,
  27061. sideOrientation: sideOrientation,
  27062. updatable: updatable
  27063. };
  27064. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  27065. };
  27066. /**
  27067. * Creates a cylinder or a cone mesh.
  27068. * Please consider using the same method from the MeshBuilder class instead.
  27069. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  27070. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  27071. * 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.
  27072. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  27073. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  27074. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27075. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27076. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27077. */
  27078. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  27079. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  27080. if (scene !== undefined) {
  27081. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  27082. updatable = scene;
  27083. }
  27084. scene = subdivisions;
  27085. subdivisions = 1;
  27086. }
  27087. var options = {
  27088. height: height,
  27089. diameterTop: diameterTop,
  27090. diameterBottom: diameterBottom,
  27091. tessellation: tessellation,
  27092. subdivisions: subdivisions,
  27093. sideOrientation: sideOrientation,
  27094. updatable: updatable
  27095. };
  27096. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  27097. };
  27098. // Torus (Code from SharpDX.org)
  27099. /**
  27100. * Creates a torus mesh.
  27101. * Please consider using the same method from the MeshBuilder class instead.
  27102. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  27103. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  27104. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  27105. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27106. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27107. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27108. */
  27109. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  27110. var options = {
  27111. diameter: diameter,
  27112. thickness: thickness,
  27113. tessellation: tessellation,
  27114. sideOrientation: sideOrientation,
  27115. updatable: updatable
  27116. };
  27117. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  27118. };
  27119. /**
  27120. * Creates a torus knot mesh.
  27121. * Please consider using the same method from the MeshBuilder class instead.
  27122. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  27123. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  27124. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  27125. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  27126. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27127. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27128. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27129. */
  27130. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  27131. var options = {
  27132. radius: radius,
  27133. tube: tube,
  27134. radialSegments: radialSegments,
  27135. tubularSegments: tubularSegments,
  27136. p: p,
  27137. q: q,
  27138. sideOrientation: sideOrientation,
  27139. updatable: updatable
  27140. };
  27141. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  27142. };
  27143. /**
  27144. * Creates a line mesh.
  27145. * Please consider using the same method from the MeshBuilder class instead.
  27146. * 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.
  27147. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27148. * The parameter `points` is an array successive Vector3.
  27149. * 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
  27150. * When updating an instance, remember that only point positions can change, not the number of points.
  27151. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27152. */
  27153. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  27154. if (scene === void 0) { scene = null; }
  27155. if (updatable === void 0) { updatable = false; }
  27156. if (instance === void 0) { instance = null; }
  27157. var options = {
  27158. points: points,
  27159. updatable: updatable,
  27160. instance: instance
  27161. };
  27162. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  27163. };
  27164. /**
  27165. * Creates a dashed line mesh.
  27166. * Please consider using the same method from the MeshBuilder class instead.
  27167. * 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.
  27168. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27169. * The parameter `points` is an array successive Vector3.
  27170. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  27171. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  27172. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  27173. * 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
  27174. * When updating an instance, remember that only point positions can change, not the number of points.
  27175. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27176. */
  27177. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  27178. if (scene === void 0) { scene = null; }
  27179. var options = {
  27180. points: points,
  27181. dashSize: dashSize,
  27182. gapSize: gapSize,
  27183. dashNb: dashNb,
  27184. updatable: updatable,
  27185. instance: instance
  27186. };
  27187. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  27188. };
  27189. /**
  27190. * Creates a polygon mesh.
  27191. * Please consider using the same method from the MeshBuilder class instead.
  27192. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  27193. * 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.
  27194. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27195. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27196. * Remember you can only change the shape positions, not their number when updating a polygon.
  27197. */
  27198. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  27199. var options = {
  27200. shape: shape,
  27201. holes: holes,
  27202. updatable: updatable,
  27203. sideOrientation: sideOrientation
  27204. };
  27205. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  27206. };
  27207. /**
  27208. * Creates an extruded polygon mesh, with depth in the Y direction.
  27209. * Please consider using the same method from the MeshBuilder class instead.
  27210. */
  27211. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  27212. var options = {
  27213. shape: shape,
  27214. holes: holes,
  27215. depth: depth,
  27216. updatable: updatable,
  27217. sideOrientation: sideOrientation
  27218. };
  27219. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  27220. };
  27221. /**
  27222. * Creates an extruded shape mesh.
  27223. * 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.
  27224. * Please consider using the same method from the MeshBuilder class instead.
  27225. *
  27226. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27227. * 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
  27228. * extruded along the Z axis.
  27229. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27230. * 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.
  27231. * The parameter `scale` (float, default 1) is the value to scale the shape.
  27232. * 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
  27233. * 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
  27234. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27235. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27236. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27237. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27238. */
  27239. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  27240. if (scene === void 0) { scene = null; }
  27241. var options = {
  27242. shape: shape,
  27243. path: path,
  27244. scale: scale,
  27245. rotation: rotation,
  27246. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27247. sideOrientation: sideOrientation,
  27248. instance: instance,
  27249. updatable: updatable
  27250. };
  27251. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  27252. };
  27253. /**
  27254. * Creates an custom extruded shape mesh.
  27255. * 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.
  27256. * Please consider using the same method from the MeshBuilder class instead.
  27257. *
  27258. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27259. * 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
  27260. * extruded along the Z axis.
  27261. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27262. * 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
  27263. * and the distance of this point from the begining of the path :
  27264. * ```javascript
  27265. * var rotationFunction = function(i, distance) {
  27266. * // do things
  27267. * return rotationValue; }
  27268. * ```
  27269. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  27270. * 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
  27271. * and the distance of this point from the begining of the path :
  27272. * ```javascript
  27273. * var scaleFunction = function(i, distance) {
  27274. * // do things
  27275. * return scaleValue;}
  27276. * ```
  27277. * It must returns a float value that will be the scale value applied to the shape on each path point.
  27278. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  27279. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  27280. * 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
  27281. * 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
  27282. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27283. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27284. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27285. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27286. */
  27287. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  27288. var options = {
  27289. shape: shape,
  27290. path: path,
  27291. scaleFunction: scaleFunction,
  27292. rotationFunction: rotationFunction,
  27293. ribbonCloseArray: ribbonCloseArray,
  27294. ribbonClosePath: ribbonClosePath,
  27295. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27296. sideOrientation: sideOrientation,
  27297. instance: instance,
  27298. updatable: updatable
  27299. };
  27300. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  27301. };
  27302. /**
  27303. * Creates lathe mesh.
  27304. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  27305. * Please consider using the same method from the MeshBuilder class instead.
  27306. * 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
  27307. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  27308. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  27309. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  27310. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27311. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27312. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27313. */
  27314. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  27315. var options = {
  27316. shape: shape,
  27317. radius: radius,
  27318. tessellation: tessellation,
  27319. sideOrientation: sideOrientation,
  27320. updatable: updatable
  27321. };
  27322. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  27323. };
  27324. /**
  27325. * Creates a plane mesh.
  27326. * Please consider using the same method from the MeshBuilder class instead.
  27327. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  27328. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27329. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27330. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27331. */
  27332. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  27333. var options = {
  27334. size: size,
  27335. width: size,
  27336. height: size,
  27337. sideOrientation: sideOrientation,
  27338. updatable: updatable
  27339. };
  27340. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  27341. };
  27342. /**
  27343. * Creates a ground mesh.
  27344. * Please consider using the same method from the MeshBuilder class instead.
  27345. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  27346. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  27347. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27348. */
  27349. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  27350. var options = {
  27351. width: width,
  27352. height: height,
  27353. subdivisions: subdivisions,
  27354. updatable: updatable
  27355. };
  27356. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  27357. };
  27358. /**
  27359. * Creates a tiled ground mesh.
  27360. * Please consider using the same method from the MeshBuilder class instead.
  27361. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  27362. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  27363. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  27364. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  27365. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  27366. * numbers of subdivisions on the ground width and height of each tile.
  27367. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27368. */
  27369. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  27370. var options = {
  27371. xmin: xmin,
  27372. zmin: zmin,
  27373. xmax: xmax,
  27374. zmax: zmax,
  27375. subdivisions: subdivisions,
  27376. precision: precision,
  27377. updatable: updatable
  27378. };
  27379. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  27380. };
  27381. /**
  27382. * Creates a ground mesh from a height map.
  27383. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  27384. * Please consider using the same method from the MeshBuilder class instead.
  27385. * The parameter `url` sets the URL of the height map image resource.
  27386. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  27387. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  27388. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  27389. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  27390. * 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).
  27391. * This function is passed the newly built mesh :
  27392. * ```javascript
  27393. * function(mesh) { // do things
  27394. * return; }
  27395. * ```
  27396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27397. */
  27398. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  27399. var options = {
  27400. width: width,
  27401. height: height,
  27402. subdivisions: subdivisions,
  27403. minHeight: minHeight,
  27404. maxHeight: maxHeight,
  27405. updatable: updatable,
  27406. onReady: onReady
  27407. };
  27408. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  27409. };
  27410. /**
  27411. * Creates a tube mesh.
  27412. * 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.
  27413. * Please consider using the same method from the MeshBuilder class instead.
  27414. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  27415. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  27416. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  27417. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  27418. * 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.
  27419. * It must return a radius value (positive float) :
  27420. * ```javascript
  27421. * var radiusFunction = function(i, distance) {
  27422. * // do things
  27423. * return radius; }
  27424. * ```
  27425. * 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
  27426. * 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
  27427. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27428. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27429. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27430. */
  27431. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  27432. var options = {
  27433. path: path,
  27434. radius: radius,
  27435. tessellation: tessellation,
  27436. radiusFunction: radiusFunction,
  27437. arc: 1,
  27438. cap: cap,
  27439. updatable: updatable,
  27440. sideOrientation: sideOrientation,
  27441. instance: instance
  27442. };
  27443. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  27444. };
  27445. /**
  27446. * Creates a polyhedron mesh.
  27447. * Please consider using the same method from the MeshBuilder class instead.
  27448. * 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
  27449. * to choose the wanted type.
  27450. * The parameter `size` (positive float, default 1) sets the polygon size.
  27451. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  27452. * 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`.
  27453. * 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
  27454. * 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)`).
  27455. * 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
  27456. * 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.
  27457. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27458. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27459. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27460. */
  27461. Mesh.CreatePolyhedron = function (name, options, scene) {
  27462. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  27463. };
  27464. /**
  27465. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  27466. * Please consider using the same method from the MeshBuilder class instead.
  27467. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  27468. * 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`).
  27469. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  27470. * 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.
  27471. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27472. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27473. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27474. */
  27475. Mesh.CreateIcoSphere = function (name, options, scene) {
  27476. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  27477. };
  27478. /**
  27479. * Creates a decal mesh.
  27480. * Please consider using the same method from the MeshBuilder class instead.
  27481. * 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.
  27482. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  27483. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  27484. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  27485. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  27486. */
  27487. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  27488. var options = {
  27489. position: position,
  27490. normal: normal,
  27491. size: size,
  27492. angle: angle
  27493. };
  27494. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  27495. };
  27496. // Skeletons
  27497. /**
  27498. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27499. */
  27500. Mesh.prototype.setPositionsForCPUSkinning = function () {
  27501. if (!this._sourcePositions) {
  27502. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27503. if (!source) {
  27504. return this._sourcePositions;
  27505. }
  27506. this._sourcePositions = new Float32Array(source);
  27507. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  27508. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  27509. }
  27510. }
  27511. return this._sourcePositions;
  27512. };
  27513. /**
  27514. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27515. */
  27516. Mesh.prototype.setNormalsForCPUSkinning = function () {
  27517. if (!this._sourceNormals) {
  27518. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27519. if (!source) {
  27520. return this._sourceNormals;
  27521. }
  27522. this._sourceNormals = new Float32Array(source);
  27523. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  27524. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  27525. }
  27526. }
  27527. return this._sourceNormals;
  27528. };
  27529. /**
  27530. * Updates the vertex buffer by applying transformation from the bones.
  27531. * Returns the Mesh.
  27532. *
  27533. * @param {skeleton} skeleton to apply
  27534. */
  27535. Mesh.prototype.applySkeleton = function (skeleton) {
  27536. if (!this.geometry) {
  27537. return this;
  27538. }
  27539. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  27540. return this;
  27541. }
  27542. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  27543. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27544. return this;
  27545. }
  27546. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27547. return this;
  27548. }
  27549. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27550. return this;
  27551. }
  27552. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27553. return this;
  27554. }
  27555. if (!this._sourcePositions) {
  27556. var submeshes = this.subMeshes.slice();
  27557. this.setPositionsForCPUSkinning();
  27558. this.subMeshes = submeshes;
  27559. }
  27560. if (!this._sourceNormals) {
  27561. this.setNormalsForCPUSkinning();
  27562. }
  27563. // positionsData checks for not being Float32Array will only pass at most once
  27564. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27565. if (!positionsData) {
  27566. return this;
  27567. }
  27568. if (!(positionsData instanceof Float32Array)) {
  27569. positionsData = new Float32Array(positionsData);
  27570. }
  27571. // normalsData checks for not being Float32Array will only pass at most once
  27572. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27573. if (!normalsData) {
  27574. return this;
  27575. }
  27576. if (!(normalsData instanceof Float32Array)) {
  27577. normalsData = new Float32Array(normalsData);
  27578. }
  27579. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27580. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27581. if (!matricesWeightsData || !matricesIndicesData) {
  27582. return this;
  27583. }
  27584. var needExtras = this.numBoneInfluencers > 4;
  27585. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27586. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27587. var skeletonMatrices = skeleton.getTransformMatrices(this);
  27588. var tempVector3 = BABYLON.Vector3.Zero();
  27589. var finalMatrix = new BABYLON.Matrix();
  27590. var tempMatrix = new BABYLON.Matrix();
  27591. var matWeightIdx = 0;
  27592. var inf;
  27593. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  27594. var weight;
  27595. for (inf = 0; inf < 4; inf++) {
  27596. weight = matricesWeightsData[matWeightIdx + inf];
  27597. if (weight > 0) {
  27598. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27599. finalMatrix.addToSelf(tempMatrix);
  27600. }
  27601. else
  27602. break;
  27603. }
  27604. if (needExtras) {
  27605. for (inf = 0; inf < 4; inf++) {
  27606. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27607. if (weight > 0) {
  27608. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27609. finalMatrix.addToSelf(tempMatrix);
  27610. }
  27611. else
  27612. break;
  27613. }
  27614. }
  27615. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  27616. tempVector3.toArray(positionsData, index);
  27617. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  27618. tempVector3.toArray(normalsData, index);
  27619. finalMatrix.reset();
  27620. }
  27621. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  27622. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  27623. return this;
  27624. };
  27625. // Tools
  27626. /**
  27627. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  27628. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  27629. */
  27630. Mesh.MinMax = function (meshes) {
  27631. var minVector = null;
  27632. var maxVector = null;
  27633. meshes.forEach(function (mesh, index, array) {
  27634. var boundingInfo = mesh.getBoundingInfo();
  27635. var boundingBox = boundingInfo.boundingBox;
  27636. if (!minVector || !maxVector) {
  27637. minVector = boundingBox.minimumWorld;
  27638. maxVector = boundingBox.maximumWorld;
  27639. }
  27640. else {
  27641. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  27642. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  27643. }
  27644. });
  27645. if (!minVector || !maxVector) {
  27646. return {
  27647. min: BABYLON.Vector3.Zero(),
  27648. max: BABYLON.Vector3.Zero()
  27649. };
  27650. }
  27651. return {
  27652. min: minVector,
  27653. max: maxVector
  27654. };
  27655. };
  27656. /**
  27657. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  27658. */
  27659. Mesh.Center = function (meshesOrMinMaxVector) {
  27660. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  27661. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  27662. };
  27663. /**
  27664. * Merge the array of meshes into a single mesh for performance reasons.
  27665. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  27666. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  27667. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  27668. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  27669. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  27670. */
  27671. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  27672. if (disposeSource === void 0) { disposeSource = true; }
  27673. var index;
  27674. if (!allow32BitsIndices) {
  27675. var totalVertices = 0;
  27676. // Counting vertices
  27677. for (index = 0; index < meshes.length; index++) {
  27678. if (meshes[index]) {
  27679. totalVertices += meshes[index].getTotalVertices();
  27680. if (totalVertices > 65536) {
  27681. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  27682. return null;
  27683. }
  27684. }
  27685. }
  27686. }
  27687. // Merge
  27688. var vertexData = null;
  27689. var otherVertexData;
  27690. var indiceArray = new Array();
  27691. var source = null;
  27692. for (index = 0; index < meshes.length; index++) {
  27693. if (meshes[index]) {
  27694. meshes[index].computeWorldMatrix(true);
  27695. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  27696. otherVertexData.transform(meshes[index].getWorldMatrix());
  27697. if (vertexData) {
  27698. vertexData.merge(otherVertexData);
  27699. }
  27700. else {
  27701. vertexData = otherVertexData;
  27702. source = meshes[index];
  27703. }
  27704. if (subdivideWithSubMeshes) {
  27705. indiceArray.push(meshes[index].getTotalIndices());
  27706. }
  27707. }
  27708. }
  27709. source = source;
  27710. if (!meshSubclass) {
  27711. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  27712. }
  27713. vertexData.applyToMesh(meshSubclass);
  27714. // Setting properties
  27715. meshSubclass.material = source.material;
  27716. meshSubclass.checkCollisions = source.checkCollisions;
  27717. // Cleaning
  27718. if (disposeSource) {
  27719. for (index = 0; index < meshes.length; index++) {
  27720. if (meshes[index]) {
  27721. meshes[index].dispose();
  27722. }
  27723. }
  27724. }
  27725. // Subdivide
  27726. if (subdivideWithSubMeshes) {
  27727. //-- Suppresions du submesh global
  27728. meshSubclass.releaseSubMeshes();
  27729. index = 0;
  27730. var offset = 0;
  27731. //-- aplique la subdivision en fonction du tableau d'indices
  27732. while (index < indiceArray.length) {
  27733. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  27734. offset += indiceArray[index];
  27735. index++;
  27736. }
  27737. }
  27738. return meshSubclass;
  27739. };
  27740. // Consts
  27741. Mesh._FRONTSIDE = 0;
  27742. Mesh._BACKSIDE = 1;
  27743. Mesh._DOUBLESIDE = 2;
  27744. Mesh._DEFAULTSIDE = 0;
  27745. Mesh._NO_CAP = 0;
  27746. Mesh._CAP_START = 1;
  27747. Mesh._CAP_END = 2;
  27748. Mesh._CAP_ALL = 3;
  27749. return Mesh;
  27750. }(BABYLON.AbstractMesh));
  27751. BABYLON.Mesh = Mesh;
  27752. })(BABYLON || (BABYLON = {}));
  27753. //# sourceMappingURL=babylon.mesh.js.map
  27754. var BABYLON;
  27755. (function (BABYLON) {
  27756. var BaseSubMesh = /** @class */ (function () {
  27757. function BaseSubMesh() {
  27758. }
  27759. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  27760. get: function () {
  27761. return this._materialEffect;
  27762. },
  27763. enumerable: true,
  27764. configurable: true
  27765. });
  27766. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  27767. if (defines === void 0) { defines = null; }
  27768. if (this._materialEffect === effect) {
  27769. if (!effect) {
  27770. this._materialDefines = null;
  27771. }
  27772. return;
  27773. }
  27774. this._materialDefines = defines;
  27775. this._materialEffect = effect;
  27776. };
  27777. return BaseSubMesh;
  27778. }());
  27779. BABYLON.BaseSubMesh = BaseSubMesh;
  27780. var SubMesh = /** @class */ (function (_super) {
  27781. __extends(SubMesh, _super);
  27782. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27783. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27784. var _this = _super.call(this) || this;
  27785. _this.materialIndex = materialIndex;
  27786. _this.verticesStart = verticesStart;
  27787. _this.verticesCount = verticesCount;
  27788. _this.indexStart = indexStart;
  27789. _this.indexCount = indexCount;
  27790. _this._renderId = 0;
  27791. _this._mesh = mesh;
  27792. _this._renderingMesh = renderingMesh || mesh;
  27793. mesh.subMeshes.push(_this);
  27794. _this._trianglePlanes = [];
  27795. _this._id = mesh.subMeshes.length - 1;
  27796. if (createBoundingBox) {
  27797. _this.refreshBoundingInfo();
  27798. mesh.computeWorldMatrix(true);
  27799. }
  27800. return _this;
  27801. }
  27802. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27803. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27804. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  27805. };
  27806. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  27807. get: function () {
  27808. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  27809. },
  27810. enumerable: true,
  27811. configurable: true
  27812. });
  27813. /**
  27814. * Returns the submesh BoudingInfo object.
  27815. */
  27816. SubMesh.prototype.getBoundingInfo = function () {
  27817. if (this.IsGlobal) {
  27818. return this._mesh.getBoundingInfo();
  27819. }
  27820. return this._boundingInfo;
  27821. };
  27822. /**
  27823. * Sets the submesh BoundingInfo.
  27824. * Return the SubMesh.
  27825. */
  27826. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  27827. this._boundingInfo = boundingInfo;
  27828. return this;
  27829. };
  27830. /**
  27831. * Returns the mesh of the current submesh.
  27832. */
  27833. SubMesh.prototype.getMesh = function () {
  27834. return this._mesh;
  27835. };
  27836. /**
  27837. * Returns the rendering mesh of the submesh.
  27838. */
  27839. SubMesh.prototype.getRenderingMesh = function () {
  27840. return this._renderingMesh;
  27841. };
  27842. /**
  27843. * Returns the submesh material.
  27844. */
  27845. SubMesh.prototype.getMaterial = function () {
  27846. var rootMaterial = this._renderingMesh.material;
  27847. if (rootMaterial === null || rootMaterial === undefined) {
  27848. return this._mesh.getScene().defaultMaterial;
  27849. }
  27850. else if (rootMaterial.getSubMaterial) {
  27851. var multiMaterial = rootMaterial;
  27852. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  27853. if (this._currentMaterial !== effectiveMaterial) {
  27854. this._currentMaterial = effectiveMaterial;
  27855. this._materialDefines = null;
  27856. }
  27857. return effectiveMaterial;
  27858. }
  27859. return rootMaterial;
  27860. };
  27861. // Methods
  27862. /**
  27863. * Sets a new updated BoundingInfo object to the submesh.
  27864. * Returns the SubMesh.
  27865. */
  27866. SubMesh.prototype.refreshBoundingInfo = function () {
  27867. this._lastColliderWorldVertices = null;
  27868. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  27869. return this;
  27870. }
  27871. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27872. if (!data) {
  27873. this._boundingInfo = this._mesh.getBoundingInfo();
  27874. return this;
  27875. }
  27876. var indices = this._renderingMesh.getIndices();
  27877. var extend;
  27878. //is this the only submesh?
  27879. if (this.indexStart === 0 && this.indexCount === indices.length) {
  27880. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27881. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  27882. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  27883. }
  27884. else {
  27885. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  27886. }
  27887. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27888. return this;
  27889. };
  27890. SubMesh.prototype._checkCollision = function (collider) {
  27891. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27892. return boundingInfo._checkCollision(collider);
  27893. };
  27894. /**
  27895. * Updates the submesh BoundingInfo.
  27896. * Returns the Submesh.
  27897. */
  27898. SubMesh.prototype.updateBoundingInfo = function (world) {
  27899. var boundingInfo = this.getBoundingInfo();
  27900. if (!boundingInfo) {
  27901. this.refreshBoundingInfo();
  27902. boundingInfo = this.getBoundingInfo();
  27903. }
  27904. boundingInfo.update(world);
  27905. return this;
  27906. };
  27907. /**
  27908. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  27909. * Boolean returned.
  27910. */
  27911. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  27912. var boundingInfo = this.getBoundingInfo();
  27913. if (!boundingInfo) {
  27914. return false;
  27915. }
  27916. return boundingInfo.isInFrustum(frustumPlanes);
  27917. };
  27918. /**
  27919. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  27920. * Boolean returned.
  27921. */
  27922. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  27923. var boundingInfo = this.getBoundingInfo();
  27924. if (!boundingInfo) {
  27925. return false;
  27926. }
  27927. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  27928. };
  27929. /**
  27930. * Renders the submesh.
  27931. * Returns it.
  27932. */
  27933. SubMesh.prototype.render = function (enableAlphaMode) {
  27934. this._renderingMesh.render(this, enableAlphaMode);
  27935. return this;
  27936. };
  27937. /**
  27938. * Returns a new Index Buffer.
  27939. * Type returned : WebGLBuffer.
  27940. */
  27941. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  27942. if (!this._linesIndexBuffer) {
  27943. var linesIndices = [];
  27944. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27945. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  27946. }
  27947. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  27948. this.linesIndexCount = linesIndices.length;
  27949. }
  27950. return this._linesIndexBuffer;
  27951. };
  27952. /**
  27953. * True is the passed Ray intersects the submesh bounding box.
  27954. * Boolean returned.
  27955. */
  27956. SubMesh.prototype.canIntersects = function (ray) {
  27957. var boundingInfo = this.getBoundingInfo();
  27958. if (!boundingInfo) {
  27959. return false;
  27960. }
  27961. return ray.intersectsBox(boundingInfo.boundingBox);
  27962. };
  27963. /**
  27964. * Returns an object IntersectionInfo.
  27965. */
  27966. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  27967. var intersectInfo = null;
  27968. // LineMesh first as it's also a Mesh...
  27969. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  27970. var lineMesh = this._mesh;
  27971. // Line test
  27972. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  27973. var p0 = positions[indices[index]];
  27974. var p1 = positions[indices[index + 1]];
  27975. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  27976. if (length < 0) {
  27977. continue;
  27978. }
  27979. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  27980. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  27981. if (fastCheck) {
  27982. break;
  27983. }
  27984. }
  27985. }
  27986. }
  27987. else {
  27988. // Triangles test
  27989. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27990. var p0 = positions[indices[index]];
  27991. var p1 = positions[indices[index + 1]];
  27992. var p2 = positions[indices[index + 2]];
  27993. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  27994. if (currentIntersectInfo) {
  27995. if (currentIntersectInfo.distance < 0) {
  27996. continue;
  27997. }
  27998. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  27999. intersectInfo = currentIntersectInfo;
  28000. intersectInfo.faceId = index / 3;
  28001. if (fastCheck) {
  28002. break;
  28003. }
  28004. }
  28005. }
  28006. }
  28007. }
  28008. return intersectInfo;
  28009. };
  28010. SubMesh.prototype._rebuild = function () {
  28011. if (this._linesIndexBuffer) {
  28012. this._linesIndexBuffer = null;
  28013. }
  28014. };
  28015. // Clone
  28016. /**
  28017. * Creates a new Submesh from the passed Mesh.
  28018. */
  28019. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  28020. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  28021. if (!this.IsGlobal) {
  28022. var boundingInfo = this.getBoundingInfo();
  28023. if (!boundingInfo) {
  28024. return result;
  28025. }
  28026. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  28027. }
  28028. return result;
  28029. };
  28030. // Dispose
  28031. /**
  28032. * Disposes the Submesh.
  28033. * Returns nothing.
  28034. */
  28035. SubMesh.prototype.dispose = function () {
  28036. if (this._linesIndexBuffer) {
  28037. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  28038. this._linesIndexBuffer = null;
  28039. }
  28040. // Remove from mesh
  28041. var index = this._mesh.subMeshes.indexOf(this);
  28042. this._mesh.subMeshes.splice(index, 1);
  28043. };
  28044. // Statics
  28045. /**
  28046. * Creates a new Submesh from the passed parameters :
  28047. * - materialIndex (integer) : the index of the main mesh material.
  28048. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  28049. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  28050. * - mesh (Mesh) : the main mesh to create the submesh from.
  28051. * - renderingMesh (optional Mesh) : rendering mesh.
  28052. */
  28053. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  28054. var minVertexIndex = Number.MAX_VALUE;
  28055. var maxVertexIndex = -Number.MAX_VALUE;
  28056. renderingMesh = (renderingMesh || mesh);
  28057. var indices = renderingMesh.getIndices();
  28058. for (var index = startIndex; index < startIndex + indexCount; index++) {
  28059. var vertexIndex = indices[index];
  28060. if (vertexIndex < minVertexIndex)
  28061. minVertexIndex = vertexIndex;
  28062. if (vertexIndex > maxVertexIndex)
  28063. maxVertexIndex = vertexIndex;
  28064. }
  28065. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  28066. };
  28067. return SubMesh;
  28068. }(BaseSubMesh));
  28069. BABYLON.SubMesh = SubMesh;
  28070. })(BABYLON || (BABYLON = {}));
  28071. //# sourceMappingURL=babylon.subMesh.js.map
  28072. var __assign = (this && this.__assign) || Object.assign || function(t) {
  28073. for (var s, i = 1, n = arguments.length; i < n; i++) {
  28074. s = arguments[i];
  28075. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  28076. t[p] = s[p];
  28077. }
  28078. return t;
  28079. };
  28080. var BABYLON;
  28081. (function (BABYLON) {
  28082. var MaterialDefines = /** @class */ (function () {
  28083. function MaterialDefines() {
  28084. this._isDirty = true;
  28085. this._areLightsDirty = true;
  28086. this._areAttributesDirty = true;
  28087. this._areTexturesDirty = true;
  28088. this._areFresnelDirty = true;
  28089. this._areMiscDirty = true;
  28090. this._areImageProcessingDirty = true;
  28091. this._normals = false;
  28092. this._uvs = false;
  28093. this._needNormals = false;
  28094. this._needUVs = false;
  28095. }
  28096. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  28097. get: function () {
  28098. return this._isDirty;
  28099. },
  28100. enumerable: true,
  28101. configurable: true
  28102. });
  28103. MaterialDefines.prototype.markAsProcessed = function () {
  28104. this._isDirty = false;
  28105. this._areAttributesDirty = false;
  28106. this._areTexturesDirty = false;
  28107. this._areFresnelDirty = false;
  28108. this._areLightsDirty = false;
  28109. this._areMiscDirty = false;
  28110. this._areImageProcessingDirty = false;
  28111. };
  28112. MaterialDefines.prototype.markAsUnprocessed = function () {
  28113. this._isDirty = true;
  28114. };
  28115. MaterialDefines.prototype.markAllAsDirty = function () {
  28116. this._areTexturesDirty = true;
  28117. this._areAttributesDirty = true;
  28118. this._areLightsDirty = true;
  28119. this._areFresnelDirty = true;
  28120. this._areMiscDirty = true;
  28121. this._areImageProcessingDirty = true;
  28122. this._isDirty = true;
  28123. };
  28124. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  28125. this._areImageProcessingDirty = true;
  28126. this._isDirty = true;
  28127. };
  28128. MaterialDefines.prototype.markAsLightDirty = function () {
  28129. this._areLightsDirty = true;
  28130. this._isDirty = true;
  28131. };
  28132. MaterialDefines.prototype.markAsAttributesDirty = function () {
  28133. this._areAttributesDirty = true;
  28134. this._isDirty = true;
  28135. };
  28136. MaterialDefines.prototype.markAsTexturesDirty = function () {
  28137. this._areTexturesDirty = true;
  28138. this._isDirty = true;
  28139. };
  28140. MaterialDefines.prototype.markAsFresnelDirty = function () {
  28141. this._areFresnelDirty = true;
  28142. this._isDirty = true;
  28143. };
  28144. MaterialDefines.prototype.markAsMiscDirty = function () {
  28145. this._areMiscDirty = true;
  28146. this._isDirty = true;
  28147. };
  28148. MaterialDefines.prototype.rebuild = function () {
  28149. if (this._keys) {
  28150. delete this._keys;
  28151. }
  28152. this._keys = [];
  28153. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  28154. var key = _a[_i];
  28155. if (key[0] === "_") {
  28156. continue;
  28157. }
  28158. this._keys.push(key);
  28159. }
  28160. };
  28161. MaterialDefines.prototype.isEqual = function (other) {
  28162. if (this._keys.length !== other._keys.length) {
  28163. return false;
  28164. }
  28165. for (var index = 0; index < this._keys.length; index++) {
  28166. var prop = this._keys[index];
  28167. if (this[prop] !== other[prop]) {
  28168. return false;
  28169. }
  28170. }
  28171. return true;
  28172. };
  28173. MaterialDefines.prototype.cloneTo = function (other) {
  28174. if (this._keys.length !== other._keys.length) {
  28175. other._keys = this._keys.slice(0);
  28176. }
  28177. for (var index = 0; index < this._keys.length; index++) {
  28178. var prop = this._keys[index];
  28179. other[prop] = this[prop];
  28180. }
  28181. };
  28182. MaterialDefines.prototype.reset = function () {
  28183. for (var index = 0; index < this._keys.length; index++) {
  28184. var prop = this._keys[index];
  28185. if (typeof (this[prop]) === "number") {
  28186. this[prop] = 0;
  28187. }
  28188. else {
  28189. this[prop] = false;
  28190. }
  28191. }
  28192. };
  28193. MaterialDefines.prototype.toString = function () {
  28194. var result = "";
  28195. for (var index = 0; index < this._keys.length; index++) {
  28196. var prop = this._keys[index];
  28197. var value = this[prop];
  28198. if (typeof (value) === "number") {
  28199. result += "#define " + prop + " " + this[prop] + "\n";
  28200. }
  28201. else if (value) {
  28202. result += "#define " + prop + "\n";
  28203. }
  28204. }
  28205. return result;
  28206. };
  28207. return MaterialDefines;
  28208. }());
  28209. BABYLON.MaterialDefines = MaterialDefines;
  28210. var Material = /** @class */ (function () {
  28211. function Material(name, scene, doNotAdd) {
  28212. this.checkReadyOnEveryCall = false;
  28213. this.checkReadyOnlyOnce = false;
  28214. this.state = "";
  28215. this.alpha = 1.0;
  28216. this._backFaceCulling = true;
  28217. this.doNotSerialize = false;
  28218. this.storeEffectOnSubMeshes = false;
  28219. /**
  28220. * An event triggered when the material is disposed.
  28221. * @type {BABYLON.Observable}
  28222. */
  28223. this.onDisposeObservable = new BABYLON.Observable();
  28224. /**
  28225. * An event triggered when the material is bound.
  28226. * @type {BABYLON.Observable}
  28227. */
  28228. this.onBindObservable = new BABYLON.Observable();
  28229. /**
  28230. * An event triggered when the material is unbound.
  28231. * @type {BABYLON.Observable}
  28232. */
  28233. this.onUnBindObservable = new BABYLON.Observable();
  28234. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  28235. this._needDepthPrePass = false;
  28236. this.disableDepthWrite = false;
  28237. this.forceDepthWrite = false;
  28238. this.separateCullingPass = false;
  28239. this._fogEnabled = true;
  28240. this.pointSize = 1.0;
  28241. this.zOffset = 0;
  28242. this._wasPreviouslyReady = false;
  28243. this._fillMode = Material.TriangleFillMode;
  28244. this.name = name;
  28245. this.id = name || BABYLON.Tools.RandomId();
  28246. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  28247. if (this._scene.useRightHandedSystem) {
  28248. this.sideOrientation = Material.ClockWiseSideOrientation;
  28249. }
  28250. else {
  28251. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  28252. }
  28253. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  28254. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  28255. if (!doNotAdd) {
  28256. this._scene.materials.push(this);
  28257. }
  28258. }
  28259. Object.defineProperty(Material, "TriangleFillMode", {
  28260. get: function () {
  28261. return Material._TriangleFillMode;
  28262. },
  28263. enumerable: true,
  28264. configurable: true
  28265. });
  28266. Object.defineProperty(Material, "WireFrameFillMode", {
  28267. get: function () {
  28268. return Material._WireFrameFillMode;
  28269. },
  28270. enumerable: true,
  28271. configurable: true
  28272. });
  28273. Object.defineProperty(Material, "PointFillMode", {
  28274. get: function () {
  28275. return Material._PointFillMode;
  28276. },
  28277. enumerable: true,
  28278. configurable: true
  28279. });
  28280. Object.defineProperty(Material, "PointListDrawMode", {
  28281. get: function () {
  28282. return Material._PointListDrawMode;
  28283. },
  28284. enumerable: true,
  28285. configurable: true
  28286. });
  28287. Object.defineProperty(Material, "LineListDrawMode", {
  28288. get: function () {
  28289. return Material._LineListDrawMode;
  28290. },
  28291. enumerable: true,
  28292. configurable: true
  28293. });
  28294. Object.defineProperty(Material, "LineLoopDrawMode", {
  28295. get: function () {
  28296. return Material._LineLoopDrawMode;
  28297. },
  28298. enumerable: true,
  28299. configurable: true
  28300. });
  28301. Object.defineProperty(Material, "LineStripDrawMode", {
  28302. get: function () {
  28303. return Material._LineStripDrawMode;
  28304. },
  28305. enumerable: true,
  28306. configurable: true
  28307. });
  28308. Object.defineProperty(Material, "TriangleStripDrawMode", {
  28309. get: function () {
  28310. return Material._TriangleStripDrawMode;
  28311. },
  28312. enumerable: true,
  28313. configurable: true
  28314. });
  28315. Object.defineProperty(Material, "TriangleFanDrawMode", {
  28316. get: function () {
  28317. return Material._TriangleFanDrawMode;
  28318. },
  28319. enumerable: true,
  28320. configurable: true
  28321. });
  28322. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28323. get: function () {
  28324. return Material._ClockWiseSideOrientation;
  28325. },
  28326. enumerable: true,
  28327. configurable: true
  28328. });
  28329. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28330. get: function () {
  28331. return Material._CounterClockWiseSideOrientation;
  28332. },
  28333. enumerable: true,
  28334. configurable: true
  28335. });
  28336. Object.defineProperty(Material, "TextureDirtyFlag", {
  28337. get: function () {
  28338. return Material._TextureDirtyFlag;
  28339. },
  28340. enumerable: true,
  28341. configurable: true
  28342. });
  28343. Object.defineProperty(Material, "LightDirtyFlag", {
  28344. get: function () {
  28345. return Material._LightDirtyFlag;
  28346. },
  28347. enumerable: true,
  28348. configurable: true
  28349. });
  28350. Object.defineProperty(Material, "FresnelDirtyFlag", {
  28351. get: function () {
  28352. return Material._FresnelDirtyFlag;
  28353. },
  28354. enumerable: true,
  28355. configurable: true
  28356. });
  28357. Object.defineProperty(Material, "AttributesDirtyFlag", {
  28358. get: function () {
  28359. return Material._AttributesDirtyFlag;
  28360. },
  28361. enumerable: true,
  28362. configurable: true
  28363. });
  28364. Object.defineProperty(Material, "MiscDirtyFlag", {
  28365. get: function () {
  28366. return Material._MiscDirtyFlag;
  28367. },
  28368. enumerable: true,
  28369. configurable: true
  28370. });
  28371. Object.defineProperty(Material.prototype, "backFaceCulling", {
  28372. get: function () {
  28373. return this._backFaceCulling;
  28374. },
  28375. set: function (value) {
  28376. if (this._backFaceCulling === value) {
  28377. return;
  28378. }
  28379. this._backFaceCulling = value;
  28380. this.markAsDirty(Material.TextureDirtyFlag);
  28381. },
  28382. enumerable: true,
  28383. configurable: true
  28384. });
  28385. Object.defineProperty(Material.prototype, "onDispose", {
  28386. set: function (callback) {
  28387. if (this._onDisposeObserver) {
  28388. this.onDisposeObservable.remove(this._onDisposeObserver);
  28389. }
  28390. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28391. },
  28392. enumerable: true,
  28393. configurable: true
  28394. });
  28395. Object.defineProperty(Material.prototype, "onBind", {
  28396. set: function (callback) {
  28397. if (this._onBindObserver) {
  28398. this.onBindObservable.remove(this._onBindObserver);
  28399. }
  28400. this._onBindObserver = this.onBindObservable.add(callback);
  28401. },
  28402. enumerable: true,
  28403. configurable: true
  28404. });
  28405. Object.defineProperty(Material.prototype, "alphaMode", {
  28406. get: function () {
  28407. return this._alphaMode;
  28408. },
  28409. set: function (value) {
  28410. if (this._alphaMode === value) {
  28411. return;
  28412. }
  28413. this._alphaMode = value;
  28414. this.markAsDirty(Material.TextureDirtyFlag);
  28415. },
  28416. enumerable: true,
  28417. configurable: true
  28418. });
  28419. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  28420. get: function () {
  28421. return this._needDepthPrePass;
  28422. },
  28423. set: function (value) {
  28424. if (this._needDepthPrePass === value) {
  28425. return;
  28426. }
  28427. this._needDepthPrePass = value;
  28428. if (this._needDepthPrePass) {
  28429. this.checkReadyOnEveryCall = true;
  28430. }
  28431. },
  28432. enumerable: true,
  28433. configurable: true
  28434. });
  28435. Object.defineProperty(Material.prototype, "fogEnabled", {
  28436. get: function () {
  28437. return this._fogEnabled;
  28438. },
  28439. set: function (value) {
  28440. if (this._fogEnabled === value) {
  28441. return;
  28442. }
  28443. this._fogEnabled = value;
  28444. this.markAsDirty(Material.MiscDirtyFlag);
  28445. },
  28446. enumerable: true,
  28447. configurable: true
  28448. });
  28449. Object.defineProperty(Material.prototype, "wireframe", {
  28450. get: function () {
  28451. return this._fillMode === Material.WireFrameFillMode;
  28452. },
  28453. set: function (value) {
  28454. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28455. },
  28456. enumerable: true,
  28457. configurable: true
  28458. });
  28459. Object.defineProperty(Material.prototype, "pointsCloud", {
  28460. get: function () {
  28461. return this._fillMode === Material.PointFillMode;
  28462. },
  28463. set: function (value) {
  28464. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28465. },
  28466. enumerable: true,
  28467. configurable: true
  28468. });
  28469. Object.defineProperty(Material.prototype, "fillMode", {
  28470. get: function () {
  28471. return this._fillMode;
  28472. },
  28473. set: function (value) {
  28474. if (this._fillMode === value) {
  28475. return;
  28476. }
  28477. this._fillMode = value;
  28478. this.markAsDirty(Material.MiscDirtyFlag);
  28479. },
  28480. enumerable: true,
  28481. configurable: true
  28482. });
  28483. /**
  28484. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28485. * subclasses should override adding information pertainent to themselves
  28486. */
  28487. Material.prototype.toString = function (fullDetails) {
  28488. var ret = "Name: " + this.name;
  28489. if (fullDetails) {
  28490. }
  28491. return ret;
  28492. };
  28493. /**
  28494. * Child classes can use it to update shaders
  28495. */
  28496. Material.prototype.getClassName = function () {
  28497. return "Material";
  28498. };
  28499. Object.defineProperty(Material.prototype, "isFrozen", {
  28500. get: function () {
  28501. return this.checkReadyOnlyOnce;
  28502. },
  28503. enumerable: true,
  28504. configurable: true
  28505. });
  28506. Material.prototype.freeze = function () {
  28507. this.checkReadyOnlyOnce = true;
  28508. };
  28509. Material.prototype.unfreeze = function () {
  28510. this.checkReadyOnlyOnce = false;
  28511. };
  28512. Material.prototype.isReady = function (mesh, useInstances) {
  28513. return true;
  28514. };
  28515. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28516. return false;
  28517. };
  28518. Material.prototype.getEffect = function () {
  28519. return this._effect;
  28520. };
  28521. Material.prototype.getScene = function () {
  28522. return this._scene;
  28523. };
  28524. Material.prototype.needAlphaBlending = function () {
  28525. return (this.alpha < 1.0);
  28526. };
  28527. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  28528. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  28529. };
  28530. Material.prototype.needAlphaTesting = function () {
  28531. return false;
  28532. };
  28533. Material.prototype.getAlphaTestTexture = function () {
  28534. return null;
  28535. };
  28536. Material.prototype.markDirty = function () {
  28537. this._wasPreviouslyReady = false;
  28538. };
  28539. Material.prototype._preBind = function (effect, overrideOrientation) {
  28540. if (overrideOrientation === void 0) { overrideOrientation = null; }
  28541. var engine = this._scene.getEngine();
  28542. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  28543. var reverse = orientation === Material.ClockWiseSideOrientation;
  28544. engine.enableEffect(effect ? effect : this._effect);
  28545. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  28546. return reverse;
  28547. };
  28548. Material.prototype.bind = function (world, mesh) {
  28549. };
  28550. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28551. };
  28552. Material.prototype.bindOnlyWorldMatrix = function (world) {
  28553. };
  28554. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  28555. sceneUbo.bindToEffect(effect, "Scene");
  28556. };
  28557. Material.prototype.bindView = function (effect) {
  28558. if (!this._useUBO) {
  28559. effect.setMatrix("view", this.getScene().getViewMatrix());
  28560. }
  28561. else {
  28562. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28563. }
  28564. };
  28565. Material.prototype.bindViewProjection = function (effect) {
  28566. if (!this._useUBO) {
  28567. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28568. }
  28569. else {
  28570. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28571. }
  28572. };
  28573. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  28574. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  28575. };
  28576. Material.prototype._afterBind = function (mesh) {
  28577. this._scene._cachedMaterial = this;
  28578. if (mesh) {
  28579. this._scene._cachedVisibility = mesh.visibility;
  28580. }
  28581. else {
  28582. this._scene._cachedVisibility = 1;
  28583. }
  28584. if (mesh) {
  28585. this.onBindObservable.notifyObservers(mesh);
  28586. }
  28587. if (this.disableDepthWrite) {
  28588. var engine = this._scene.getEngine();
  28589. this._cachedDepthWriteState = engine.getDepthWrite();
  28590. engine.setDepthWrite(false);
  28591. }
  28592. };
  28593. Material.prototype.unbind = function () {
  28594. this.onUnBindObservable.notifyObservers(this);
  28595. if (this.disableDepthWrite) {
  28596. var engine = this._scene.getEngine();
  28597. engine.setDepthWrite(this._cachedDepthWriteState);
  28598. }
  28599. };
  28600. Material.prototype.getActiveTextures = function () {
  28601. return [];
  28602. };
  28603. Material.prototype.hasTexture = function (texture) {
  28604. return false;
  28605. };
  28606. Material.prototype.clone = function (name) {
  28607. return null;
  28608. };
  28609. Material.prototype.getBindedMeshes = function () {
  28610. var result = new Array();
  28611. for (var index = 0; index < this._scene.meshes.length; index++) {
  28612. var mesh = this._scene.meshes[index];
  28613. if (mesh.material === this) {
  28614. result.push(mesh);
  28615. }
  28616. }
  28617. return result;
  28618. };
  28619. /**
  28620. * Force shader compilation including textures ready check
  28621. */
  28622. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  28623. var _this = this;
  28624. var localOptions = __assign({ clipPlane: false }, options);
  28625. var subMesh = new BABYLON.BaseSubMesh();
  28626. var scene = this.getScene();
  28627. var checkReady = function () {
  28628. if (!_this._scene || !_this._scene.getEngine()) {
  28629. return;
  28630. }
  28631. if (subMesh._materialDefines) {
  28632. subMesh._materialDefines._renderId = -1;
  28633. }
  28634. var clipPlaneState = scene.clipPlane;
  28635. if (localOptions.clipPlane) {
  28636. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  28637. }
  28638. if (_this.storeEffectOnSubMeshes) {
  28639. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  28640. if (onCompiled) {
  28641. onCompiled(_this);
  28642. }
  28643. }
  28644. else {
  28645. setTimeout(checkReady, 16);
  28646. }
  28647. }
  28648. else {
  28649. if (_this.isReady(mesh)) {
  28650. if (onCompiled) {
  28651. onCompiled(_this);
  28652. }
  28653. }
  28654. else {
  28655. setTimeout(checkReady, 16);
  28656. }
  28657. }
  28658. if (options && options.clipPlane) {
  28659. scene.clipPlane = clipPlaneState;
  28660. }
  28661. };
  28662. checkReady();
  28663. };
  28664. Material.prototype.markAsDirty = function (flag) {
  28665. if (flag & Material.TextureDirtyFlag) {
  28666. this._markAllSubMeshesAsTexturesDirty();
  28667. }
  28668. if (flag & Material.LightDirtyFlag) {
  28669. this._markAllSubMeshesAsLightsDirty();
  28670. }
  28671. if (flag & Material.FresnelDirtyFlag) {
  28672. this._markAllSubMeshesAsFresnelDirty();
  28673. }
  28674. if (flag & Material.AttributesDirtyFlag) {
  28675. this._markAllSubMeshesAsAttributesDirty();
  28676. }
  28677. if (flag & Material.MiscDirtyFlag) {
  28678. this._markAllSubMeshesAsMiscDirty();
  28679. }
  28680. this.getScene().resetCachedMaterial();
  28681. };
  28682. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  28683. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28684. var mesh = _a[_i];
  28685. if (!mesh.subMeshes) {
  28686. continue;
  28687. }
  28688. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28689. var subMesh = _c[_b];
  28690. if (subMesh.getMaterial() !== this) {
  28691. continue;
  28692. }
  28693. if (!subMesh._materialDefines) {
  28694. continue;
  28695. }
  28696. func(subMesh._materialDefines);
  28697. }
  28698. }
  28699. };
  28700. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28701. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28702. };
  28703. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28704. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28705. };
  28706. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28707. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28708. };
  28709. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28710. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28711. };
  28712. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28713. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28714. };
  28715. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28716. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28717. };
  28718. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28719. // Animations
  28720. this.getScene().stopAnimation(this);
  28721. // Remove from scene
  28722. var index = this._scene.materials.indexOf(this);
  28723. if (index >= 0) {
  28724. this._scene.materials.splice(index, 1);
  28725. }
  28726. // Remove from meshes
  28727. for (index = 0; index < this._scene.meshes.length; index++) {
  28728. var mesh = this._scene.meshes[index];
  28729. if (mesh.material === this) {
  28730. mesh.material = null;
  28731. if (mesh.geometry) {
  28732. var geometry = (mesh.geometry);
  28733. if (this.storeEffectOnSubMeshes) {
  28734. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28735. var subMesh = _a[_i];
  28736. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28737. if (forceDisposeEffect && subMesh._materialEffect) {
  28738. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28739. }
  28740. }
  28741. }
  28742. else {
  28743. geometry._releaseVertexArrayObject(this._effect);
  28744. }
  28745. }
  28746. }
  28747. }
  28748. this._uniformBuffer.dispose();
  28749. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28750. if (forceDisposeEffect && this._effect) {
  28751. if (!this.storeEffectOnSubMeshes) {
  28752. this._scene.getEngine()._releaseEffect(this._effect);
  28753. }
  28754. this._effect = null;
  28755. }
  28756. // Callback
  28757. this.onDisposeObservable.notifyObservers(this);
  28758. this.onDisposeObservable.clear();
  28759. this.onBindObservable.clear();
  28760. this.onUnBindObservable.clear();
  28761. };
  28762. Material.prototype.serialize = function () {
  28763. return BABYLON.SerializationHelper.Serialize(this);
  28764. };
  28765. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28766. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28767. multiMaterial.id = parsedMultiMaterial.id;
  28768. if (BABYLON.Tags) {
  28769. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28770. }
  28771. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28772. var subMatId = parsedMultiMaterial.materials[matIndex];
  28773. if (subMatId) {
  28774. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28775. }
  28776. else {
  28777. multiMaterial.subMaterials.push(null);
  28778. }
  28779. }
  28780. return multiMaterial;
  28781. };
  28782. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28783. if (!parsedMaterial.customType) {
  28784. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28785. }
  28786. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28787. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28788. if (!BABYLON.LegacyPBRMaterial) {
  28789. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28790. return;
  28791. }
  28792. }
  28793. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28794. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28795. ;
  28796. };
  28797. // Triangle views
  28798. Material._TriangleFillMode = 0;
  28799. Material._WireFrameFillMode = 1;
  28800. Material._PointFillMode = 2;
  28801. // Draw modes
  28802. Material._PointListDrawMode = 3;
  28803. Material._LineListDrawMode = 4;
  28804. Material._LineLoopDrawMode = 5;
  28805. Material._LineStripDrawMode = 6;
  28806. Material._TriangleStripDrawMode = 7;
  28807. Material._TriangleFanDrawMode = 8;
  28808. Material._ClockWiseSideOrientation = 0;
  28809. Material._CounterClockWiseSideOrientation = 1;
  28810. Material._TextureDirtyFlag = 1;
  28811. Material._LightDirtyFlag = 2;
  28812. Material._FresnelDirtyFlag = 4;
  28813. Material._AttributesDirtyFlag = 8;
  28814. Material._MiscDirtyFlag = 16;
  28815. __decorate([
  28816. BABYLON.serialize()
  28817. ], Material.prototype, "id", void 0);
  28818. __decorate([
  28819. BABYLON.serialize()
  28820. ], Material.prototype, "name", void 0);
  28821. __decorate([
  28822. BABYLON.serialize()
  28823. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28824. __decorate([
  28825. BABYLON.serialize()
  28826. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28827. __decorate([
  28828. BABYLON.serialize()
  28829. ], Material.prototype, "state", void 0);
  28830. __decorate([
  28831. BABYLON.serialize()
  28832. ], Material.prototype, "alpha", void 0);
  28833. __decorate([
  28834. BABYLON.serialize("backFaceCulling")
  28835. ], Material.prototype, "_backFaceCulling", void 0);
  28836. __decorate([
  28837. BABYLON.serialize()
  28838. ], Material.prototype, "sideOrientation", void 0);
  28839. __decorate([
  28840. BABYLON.serialize("alphaMode")
  28841. ], Material.prototype, "_alphaMode", void 0);
  28842. __decorate([
  28843. BABYLON.serialize()
  28844. ], Material.prototype, "_needDepthPrePass", void 0);
  28845. __decorate([
  28846. BABYLON.serialize()
  28847. ], Material.prototype, "disableDepthWrite", void 0);
  28848. __decorate([
  28849. BABYLON.serialize()
  28850. ], Material.prototype, "forceDepthWrite", void 0);
  28851. __decorate([
  28852. BABYLON.serialize()
  28853. ], Material.prototype, "separateCullingPass", void 0);
  28854. __decorate([
  28855. BABYLON.serialize("fogEnabled")
  28856. ], Material.prototype, "_fogEnabled", void 0);
  28857. __decorate([
  28858. BABYLON.serialize()
  28859. ], Material.prototype, "pointSize", void 0);
  28860. __decorate([
  28861. BABYLON.serialize()
  28862. ], Material.prototype, "zOffset", void 0);
  28863. __decorate([
  28864. BABYLON.serialize()
  28865. ], Material.prototype, "wireframe", null);
  28866. __decorate([
  28867. BABYLON.serialize()
  28868. ], Material.prototype, "pointsCloud", null);
  28869. __decorate([
  28870. BABYLON.serialize()
  28871. ], Material.prototype, "fillMode", null);
  28872. return Material;
  28873. }());
  28874. BABYLON.Material = Material;
  28875. })(BABYLON || (BABYLON = {}));
  28876. //# sourceMappingURL=babylon.material.js.map
  28877. var BABYLON;
  28878. (function (BABYLON) {
  28879. var UniformBuffer = /** @class */ (function () {
  28880. /**
  28881. * Uniform buffer objects.
  28882. *
  28883. * Handles blocks of uniform on the GPU.
  28884. *
  28885. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28886. *
  28887. * For more information, please refer to :
  28888. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28889. */
  28890. function UniformBuffer(engine, data, dynamic) {
  28891. this._engine = engine;
  28892. this._noUBO = !engine.supportsUniformBuffers;
  28893. this._dynamic = dynamic;
  28894. this._data = data || [];
  28895. this._uniformLocations = {};
  28896. this._uniformSizes = {};
  28897. this._uniformLocationPointer = 0;
  28898. this._needSync = false;
  28899. if (this._noUBO) {
  28900. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28901. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28902. this.updateFloat = this._updateFloatForEffect;
  28903. this.updateFloat2 = this._updateFloat2ForEffect;
  28904. this.updateFloat3 = this._updateFloat3ForEffect;
  28905. this.updateFloat4 = this._updateFloat4ForEffect;
  28906. this.updateMatrix = this._updateMatrixForEffect;
  28907. this.updateVector3 = this._updateVector3ForEffect;
  28908. this.updateVector4 = this._updateVector4ForEffect;
  28909. this.updateColor3 = this._updateColor3ForEffect;
  28910. this.updateColor4 = this._updateColor4ForEffect;
  28911. }
  28912. else {
  28913. this._engine._uniformBuffers.push(this);
  28914. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28915. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28916. this.updateFloat = this._updateFloatForUniform;
  28917. this.updateFloat2 = this._updateFloat2ForUniform;
  28918. this.updateFloat3 = this._updateFloat3ForUniform;
  28919. this.updateFloat4 = this._updateFloat4ForUniform;
  28920. this.updateMatrix = this._updateMatrixForUniform;
  28921. this.updateVector3 = this._updateVector3ForUniform;
  28922. this.updateVector4 = this._updateVector4ForUniform;
  28923. this.updateColor3 = this._updateColor3ForUniform;
  28924. this.updateColor4 = this._updateColor4ForUniform;
  28925. }
  28926. }
  28927. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28928. // Properties
  28929. /**
  28930. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28931. * or just falling back on setUniformXXX calls.
  28932. */
  28933. get: function () {
  28934. return !this._noUBO;
  28935. },
  28936. enumerable: true,
  28937. configurable: true
  28938. });
  28939. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28940. /**
  28941. * Indicates if the WebGL underlying uniform buffer is in sync
  28942. * with the javascript cache data.
  28943. */
  28944. get: function () {
  28945. return !this._needSync;
  28946. },
  28947. enumerable: true,
  28948. configurable: true
  28949. });
  28950. /**
  28951. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28952. * Also, a dynamic UniformBuffer will disable cache verification and always
  28953. * update the underlying WebGL uniform buffer to the GPU.
  28954. */
  28955. UniformBuffer.prototype.isDynamic = function () {
  28956. return this._dynamic !== undefined;
  28957. };
  28958. /**
  28959. * The data cache on JS side.
  28960. */
  28961. UniformBuffer.prototype.getData = function () {
  28962. return this._bufferData;
  28963. };
  28964. /**
  28965. * The underlying WebGL Uniform buffer.
  28966. */
  28967. UniformBuffer.prototype.getBuffer = function () {
  28968. return this._buffer;
  28969. };
  28970. /**
  28971. * std140 layout specifies how to align data within an UBO structure.
  28972. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28973. * for specs.
  28974. */
  28975. UniformBuffer.prototype._fillAlignment = function (size) {
  28976. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28977. // and 4x4 matrices
  28978. // TODO : change if other types are used
  28979. var alignment;
  28980. if (size <= 2) {
  28981. alignment = size;
  28982. }
  28983. else {
  28984. alignment = 4;
  28985. }
  28986. if ((this._uniformLocationPointer % alignment) !== 0) {
  28987. var oldPointer = this._uniformLocationPointer;
  28988. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28989. var diff = this._uniformLocationPointer - oldPointer;
  28990. for (var i = 0; i < diff; i++) {
  28991. this._data.push(0);
  28992. }
  28993. }
  28994. };
  28995. /**
  28996. * Adds an uniform in the buffer.
  28997. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28998. * for the layout to be correct !
  28999. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29000. * @param {number|number[]} size Data size, or data directly.
  29001. */
  29002. UniformBuffer.prototype.addUniform = function (name, size) {
  29003. if (this._noUBO) {
  29004. return;
  29005. }
  29006. if (this._uniformLocations[name] !== undefined) {
  29007. // Already existing uniform
  29008. return;
  29009. }
  29010. // This function must be called in the order of the shader layout !
  29011. // size can be the size of the uniform, or data directly
  29012. var data;
  29013. if (size instanceof Array) {
  29014. data = size;
  29015. size = data.length;
  29016. }
  29017. else {
  29018. size = size;
  29019. data = [];
  29020. // Fill with zeros
  29021. for (var i = 0; i < size; i++) {
  29022. data.push(0);
  29023. }
  29024. }
  29025. this._fillAlignment(size);
  29026. this._uniformSizes[name] = size;
  29027. this._uniformLocations[name] = this._uniformLocationPointer;
  29028. this._uniformLocationPointer += size;
  29029. for (var i = 0; i < size; i++) {
  29030. this._data.push(data[i]);
  29031. }
  29032. this._needSync = true;
  29033. };
  29034. /**
  29035. * Wrapper for addUniform.
  29036. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29037. * @param {Matrix} mat A 4x4 matrix.
  29038. */
  29039. UniformBuffer.prototype.addMatrix = function (name, mat) {
  29040. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  29041. };
  29042. /**
  29043. * Wrapper for addUniform.
  29044. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29045. * @param {number} x
  29046. * @param {number} y
  29047. */
  29048. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  29049. var temp = [x, y];
  29050. this.addUniform(name, temp);
  29051. };
  29052. /**
  29053. * Wrapper for addUniform.
  29054. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29055. * @param {number} x
  29056. * @param {number} y
  29057. * @param {number} z
  29058. */
  29059. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  29060. var temp = [x, y, z];
  29061. this.addUniform(name, temp);
  29062. };
  29063. /**
  29064. * Wrapper for addUniform.
  29065. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29066. * @param {Color3} color
  29067. */
  29068. UniformBuffer.prototype.addColor3 = function (name, color) {
  29069. var temp = new Array();
  29070. color.toArray(temp);
  29071. this.addUniform(name, temp);
  29072. };
  29073. /**
  29074. * Wrapper for addUniform.
  29075. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29076. * @param {Color3} color
  29077. * @param {number} alpha
  29078. */
  29079. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  29080. var temp = new Array();
  29081. color.toArray(temp);
  29082. temp.push(alpha);
  29083. this.addUniform(name, temp);
  29084. };
  29085. /**
  29086. * Wrapper for addUniform.
  29087. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29088. * @param {Vector3} vector
  29089. */
  29090. UniformBuffer.prototype.addVector3 = function (name, vector) {
  29091. var temp = new Array();
  29092. vector.toArray(temp);
  29093. this.addUniform(name, temp);
  29094. };
  29095. /**
  29096. * Wrapper for addUniform.
  29097. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29098. */
  29099. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  29100. this.addUniform(name, 12);
  29101. };
  29102. /**
  29103. * Wrapper for addUniform.
  29104. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29105. */
  29106. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  29107. this.addUniform(name, 8);
  29108. };
  29109. /**
  29110. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  29111. */
  29112. UniformBuffer.prototype.create = function () {
  29113. if (this._noUBO) {
  29114. return;
  29115. }
  29116. if (this._buffer) {
  29117. return; // nothing to do
  29118. }
  29119. // See spec, alignment must be filled as a vec4
  29120. this._fillAlignment(4);
  29121. this._bufferData = new Float32Array(this._data);
  29122. this._rebuild();
  29123. this._needSync = true;
  29124. };
  29125. UniformBuffer.prototype._rebuild = function () {
  29126. if (this._noUBO) {
  29127. return;
  29128. }
  29129. if (this._dynamic) {
  29130. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  29131. }
  29132. else {
  29133. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  29134. }
  29135. };
  29136. /**
  29137. * Updates the WebGL Uniform Buffer on the GPU.
  29138. * If the `dynamic` flag is set to true, no cache comparison is done.
  29139. * Otherwise, the buffer will be updated only if the cache differs.
  29140. */
  29141. UniformBuffer.prototype.update = function () {
  29142. if (!this._buffer) {
  29143. this.create();
  29144. return;
  29145. }
  29146. if (!this._dynamic && !this._needSync) {
  29147. return;
  29148. }
  29149. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  29150. this._needSync = false;
  29151. };
  29152. /**
  29153. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  29154. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29155. * @param {number[]|Float32Array} data Flattened data
  29156. * @param {number} size Size of the data.
  29157. */
  29158. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  29159. var location = this._uniformLocations[uniformName];
  29160. if (location === undefined) {
  29161. if (this._buffer) {
  29162. // Cannot add an uniform if the buffer is already created
  29163. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  29164. return;
  29165. }
  29166. this.addUniform(uniformName, size);
  29167. location = this._uniformLocations[uniformName];
  29168. }
  29169. if (!this._buffer) {
  29170. this.create();
  29171. }
  29172. if (!this._dynamic) {
  29173. // Cache for static uniform buffers
  29174. var changed = false;
  29175. for (var i = 0; i < size; i++) {
  29176. if (this._bufferData[location + i] !== data[i]) {
  29177. changed = true;
  29178. this._bufferData[location + i] = data[i];
  29179. }
  29180. }
  29181. this._needSync = this._needSync || changed;
  29182. }
  29183. else {
  29184. // No cache for dynamic
  29185. for (var i = 0; i < size; i++) {
  29186. this._bufferData[location + i] = data[i];
  29187. }
  29188. }
  29189. };
  29190. // Update methods
  29191. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  29192. // To match std140, matrix must be realigned
  29193. for (var i = 0; i < 3; i++) {
  29194. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  29195. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  29196. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  29197. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29198. }
  29199. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  29200. };
  29201. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  29202. this._currentEffect.setMatrix3x3(name, matrix);
  29203. };
  29204. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  29205. this._currentEffect.setMatrix2x2(name, matrix);
  29206. };
  29207. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  29208. // To match std140, matrix must be realigned
  29209. for (var i = 0; i < 2; i++) {
  29210. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  29211. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  29212. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  29213. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29214. }
  29215. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  29216. };
  29217. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  29218. this._currentEffect.setFloat(name, x);
  29219. };
  29220. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  29221. UniformBuffer._tempBuffer[0] = x;
  29222. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  29223. };
  29224. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  29225. if (suffix === void 0) { suffix = ""; }
  29226. this._currentEffect.setFloat2(name + suffix, x, y);
  29227. };
  29228. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  29229. if (suffix === void 0) { suffix = ""; }
  29230. UniformBuffer._tempBuffer[0] = x;
  29231. UniformBuffer._tempBuffer[1] = y;
  29232. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  29233. };
  29234. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  29235. if (suffix === void 0) { suffix = ""; }
  29236. this._currentEffect.setFloat3(name + suffix, x, y, z);
  29237. };
  29238. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  29239. if (suffix === void 0) { suffix = ""; }
  29240. UniformBuffer._tempBuffer[0] = x;
  29241. UniformBuffer._tempBuffer[1] = y;
  29242. UniformBuffer._tempBuffer[2] = z;
  29243. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29244. };
  29245. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  29246. if (suffix === void 0) { suffix = ""; }
  29247. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  29248. };
  29249. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  29250. if (suffix === void 0) { suffix = ""; }
  29251. UniformBuffer._tempBuffer[0] = x;
  29252. UniformBuffer._tempBuffer[1] = y;
  29253. UniformBuffer._tempBuffer[2] = z;
  29254. UniformBuffer._tempBuffer[3] = w;
  29255. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29256. };
  29257. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  29258. this._currentEffect.setMatrix(name, mat);
  29259. };
  29260. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  29261. this.updateUniform(name, mat.toArray(), 16);
  29262. };
  29263. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  29264. this._currentEffect.setVector3(name, vector);
  29265. };
  29266. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  29267. vector.toArray(UniformBuffer._tempBuffer);
  29268. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29269. };
  29270. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  29271. this._currentEffect.setVector4(name, vector);
  29272. };
  29273. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  29274. vector.toArray(UniformBuffer._tempBuffer);
  29275. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29276. };
  29277. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  29278. if (suffix === void 0) { suffix = ""; }
  29279. this._currentEffect.setColor3(name + suffix, color);
  29280. };
  29281. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  29282. if (suffix === void 0) { suffix = ""; }
  29283. color.toArray(UniformBuffer._tempBuffer);
  29284. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29285. };
  29286. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  29287. if (suffix === void 0) { suffix = ""; }
  29288. this._currentEffect.setColor4(name + suffix, color, alpha);
  29289. };
  29290. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  29291. if (suffix === void 0) { suffix = ""; }
  29292. color.toArray(UniformBuffer._tempBuffer);
  29293. UniformBuffer._tempBuffer[3] = alpha;
  29294. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29295. };
  29296. /**
  29297. * Sets a sampler uniform on the effect.
  29298. * @param {string} name Name of the sampler.
  29299. * @param {Texture} texture
  29300. */
  29301. UniformBuffer.prototype.setTexture = function (name, texture) {
  29302. this._currentEffect.setTexture(name, texture);
  29303. };
  29304. /**
  29305. * Directly updates the value of the uniform in the cache AND on the GPU.
  29306. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29307. * @param {number[]|Float32Array} data Flattened data
  29308. */
  29309. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  29310. this.updateUniform(uniformName, data, data.length);
  29311. this.update();
  29312. };
  29313. /**
  29314. * Binds this uniform buffer to an effect.
  29315. * @param {Effect} effect
  29316. * @param {string} name Name of the uniform block in the shader.
  29317. */
  29318. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  29319. this._currentEffect = effect;
  29320. if (this._noUBO || !this._buffer) {
  29321. return;
  29322. }
  29323. effect.bindUniformBuffer(this._buffer, name);
  29324. };
  29325. /**
  29326. * Disposes the uniform buffer.
  29327. */
  29328. UniformBuffer.prototype.dispose = function () {
  29329. if (this._noUBO) {
  29330. return;
  29331. }
  29332. var index = this._engine._uniformBuffers.indexOf(this);
  29333. if (index !== -1) {
  29334. this._engine._uniformBuffers.splice(index, 1);
  29335. }
  29336. if (!this._buffer) {
  29337. return;
  29338. }
  29339. if (this._engine._releaseBuffer(this._buffer)) {
  29340. this._buffer = null;
  29341. }
  29342. };
  29343. // Pool for avoiding memory leaks
  29344. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  29345. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  29346. return UniformBuffer;
  29347. }());
  29348. BABYLON.UniformBuffer = UniformBuffer;
  29349. })(BABYLON || (BABYLON = {}));
  29350. //# sourceMappingURL=babylon.uniformBuffer.js.map
  29351. var BABYLON;
  29352. (function (BABYLON) {
  29353. var VertexData = /** @class */ (function () {
  29354. function VertexData() {
  29355. }
  29356. VertexData.prototype.set = function (data, kind) {
  29357. switch (kind) {
  29358. case BABYLON.VertexBuffer.PositionKind:
  29359. this.positions = data;
  29360. break;
  29361. case BABYLON.VertexBuffer.NormalKind:
  29362. this.normals = data;
  29363. break;
  29364. case BABYLON.VertexBuffer.TangentKind:
  29365. this.tangents = data;
  29366. break;
  29367. case BABYLON.VertexBuffer.UVKind:
  29368. this.uvs = data;
  29369. break;
  29370. case BABYLON.VertexBuffer.UV2Kind:
  29371. this.uvs2 = data;
  29372. break;
  29373. case BABYLON.VertexBuffer.UV3Kind:
  29374. this.uvs3 = data;
  29375. break;
  29376. case BABYLON.VertexBuffer.UV4Kind:
  29377. this.uvs4 = data;
  29378. break;
  29379. case BABYLON.VertexBuffer.UV5Kind:
  29380. this.uvs5 = data;
  29381. break;
  29382. case BABYLON.VertexBuffer.UV6Kind:
  29383. this.uvs6 = data;
  29384. break;
  29385. case BABYLON.VertexBuffer.ColorKind:
  29386. this.colors = data;
  29387. break;
  29388. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29389. this.matricesIndices = data;
  29390. break;
  29391. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29392. this.matricesWeights = data;
  29393. break;
  29394. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29395. this.matricesIndicesExtra = data;
  29396. break;
  29397. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29398. this.matricesWeightsExtra = data;
  29399. break;
  29400. }
  29401. };
  29402. /**
  29403. * Associates the vertexData to the passed Mesh.
  29404. * Sets it as updatable or not (default `false`).
  29405. * Returns the VertexData.
  29406. */
  29407. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29408. this._applyTo(mesh, updatable);
  29409. return this;
  29410. };
  29411. /**
  29412. * Associates the vertexData to the passed Geometry.
  29413. * Sets it as updatable or not (default `false`).
  29414. * Returns the VertexData.
  29415. */
  29416. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29417. this._applyTo(geometry, updatable);
  29418. return this;
  29419. };
  29420. /**
  29421. * Updates the associated mesh.
  29422. * Returns the VertexData.
  29423. */
  29424. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29425. this._update(mesh);
  29426. return this;
  29427. };
  29428. /**
  29429. * Updates the associated geometry.
  29430. * Returns the VertexData.
  29431. */
  29432. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29433. this._update(geometry);
  29434. return this;
  29435. };
  29436. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29437. if (updatable === void 0) { updatable = false; }
  29438. if (this.positions) {
  29439. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29440. }
  29441. if (this.normals) {
  29442. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29443. }
  29444. if (this.tangents) {
  29445. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  29446. }
  29447. if (this.uvs) {
  29448. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29449. }
  29450. if (this.uvs2) {
  29451. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29452. }
  29453. if (this.uvs3) {
  29454. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29455. }
  29456. if (this.uvs4) {
  29457. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29458. }
  29459. if (this.uvs5) {
  29460. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29461. }
  29462. if (this.uvs6) {
  29463. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29464. }
  29465. if (this.colors) {
  29466. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29467. }
  29468. if (this.matricesIndices) {
  29469. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29470. }
  29471. if (this.matricesWeights) {
  29472. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29473. }
  29474. if (this.matricesIndicesExtra) {
  29475. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29476. }
  29477. if (this.matricesWeightsExtra) {
  29478. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29479. }
  29480. if (this.indices) {
  29481. meshOrGeometry.setIndices(this.indices, null, updatable);
  29482. }
  29483. return this;
  29484. };
  29485. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29486. if (this.positions) {
  29487. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29488. }
  29489. if (this.normals) {
  29490. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29491. }
  29492. if (this.tangents) {
  29493. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  29494. }
  29495. if (this.uvs) {
  29496. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29497. }
  29498. if (this.uvs2) {
  29499. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29500. }
  29501. if (this.uvs3) {
  29502. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29503. }
  29504. if (this.uvs4) {
  29505. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29506. }
  29507. if (this.uvs5) {
  29508. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29509. }
  29510. if (this.uvs6) {
  29511. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29512. }
  29513. if (this.colors) {
  29514. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29515. }
  29516. if (this.matricesIndices) {
  29517. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29518. }
  29519. if (this.matricesWeights) {
  29520. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29521. }
  29522. if (this.matricesIndicesExtra) {
  29523. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29524. }
  29525. if (this.matricesWeightsExtra) {
  29526. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29527. }
  29528. if (this.indices) {
  29529. meshOrGeometry.setIndices(this.indices, null);
  29530. }
  29531. return this;
  29532. };
  29533. /**
  29534. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  29535. * Returns the VertexData.
  29536. */
  29537. VertexData.prototype.transform = function (matrix) {
  29538. var transformed = BABYLON.Vector3.Zero();
  29539. var index;
  29540. if (this.positions) {
  29541. var position = BABYLON.Vector3.Zero();
  29542. for (index = 0; index < this.positions.length; index += 3) {
  29543. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29544. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29545. this.positions[index] = transformed.x;
  29546. this.positions[index + 1] = transformed.y;
  29547. this.positions[index + 2] = transformed.z;
  29548. }
  29549. }
  29550. if (this.normals) {
  29551. var normal = BABYLON.Vector3.Zero();
  29552. for (index = 0; index < this.normals.length; index += 3) {
  29553. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29554. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29555. this.normals[index] = transformed.x;
  29556. this.normals[index + 1] = transformed.y;
  29557. this.normals[index + 2] = transformed.z;
  29558. }
  29559. }
  29560. if (this.tangents) {
  29561. var tangent = BABYLON.Vector4.Zero();
  29562. var tangentTransformed = BABYLON.Vector4.Zero();
  29563. for (index = 0; index < this.tangents.length; index += 4) {
  29564. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  29565. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  29566. this.tangents[index] = tangentTransformed.x;
  29567. this.tangents[index + 1] = tangentTransformed.y;
  29568. this.tangents[index + 2] = tangentTransformed.z;
  29569. this.tangents[index + 3] = tangentTransformed.w;
  29570. }
  29571. }
  29572. return this;
  29573. };
  29574. /**
  29575. * Merges the passed VertexData into the current one.
  29576. * Returns the modified VertexData.
  29577. */
  29578. VertexData.prototype.merge = function (other, options) {
  29579. options = options || {};
  29580. if (other.indices) {
  29581. if (!this.indices) {
  29582. this.indices = [];
  29583. }
  29584. var offset = this.positions ? this.positions.length / 3 : 0;
  29585. for (var index = 0; index < other.indices.length; index++) {
  29586. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  29587. this.indices.push(other.indices[index] + offset);
  29588. }
  29589. }
  29590. this.positions = this._mergeElement(this.positions, other.positions);
  29591. if (!this.positions) {
  29592. return this;
  29593. }
  29594. var count = this.positions.length / 3;
  29595. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  29596. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  29597. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  29598. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  29599. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  29600. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  29601. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  29602. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  29603. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  29604. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  29605. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  29606. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  29607. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  29608. return this;
  29609. };
  29610. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  29611. if (length === void 0) { length = 0; }
  29612. if (defaultValue === void 0) { defaultValue = 0; }
  29613. if (!other && !source) {
  29614. return null;
  29615. }
  29616. if (!other) {
  29617. var padding = new Float32Array(source.length);
  29618. padding.fill(defaultValue);
  29619. return this._mergeElement(source, padding, length);
  29620. }
  29621. if (!source) {
  29622. if (length === 0 || length === other.length) {
  29623. return other;
  29624. }
  29625. var padding = new Float32Array(length - other.length);
  29626. padding.fill(defaultValue);
  29627. return this._mergeElement(padding, other, length);
  29628. }
  29629. var len = other.length + source.length;
  29630. var isSrcTypedArray = source instanceof Float32Array;
  29631. var isOthTypedArray = other instanceof Float32Array;
  29632. // use non-loop method when the source is Float32Array
  29633. if (isSrcTypedArray) {
  29634. var ret32 = new Float32Array(len);
  29635. ret32.set(source);
  29636. ret32.set(other, source.length);
  29637. return ret32;
  29638. // source is number[], when other is also use concat
  29639. }
  29640. else if (!isOthTypedArray) {
  29641. return source.concat(other);
  29642. // source is a number[], but other is a Float32Array, loop required
  29643. }
  29644. else {
  29645. var ret = source.slice(0); // copy source to a separate array
  29646. for (var i = 0, len = other.length; i < len; i++) {
  29647. ret.push(other[i]);
  29648. }
  29649. return ret;
  29650. }
  29651. };
  29652. /**
  29653. * Serializes the VertexData.
  29654. * Returns a serialized object.
  29655. */
  29656. VertexData.prototype.serialize = function () {
  29657. var serializationObject = this.serialize();
  29658. if (this.positions) {
  29659. serializationObject.positions = this.positions;
  29660. }
  29661. if (this.normals) {
  29662. serializationObject.normals = this.normals;
  29663. }
  29664. if (this.tangents) {
  29665. serializationObject.tangents = this.tangents;
  29666. }
  29667. if (this.uvs) {
  29668. serializationObject.uvs = this.uvs;
  29669. }
  29670. if (this.uvs2) {
  29671. serializationObject.uvs2 = this.uvs2;
  29672. }
  29673. if (this.uvs3) {
  29674. serializationObject.uvs3 = this.uvs3;
  29675. }
  29676. if (this.uvs4) {
  29677. serializationObject.uvs4 = this.uvs4;
  29678. }
  29679. if (this.uvs5) {
  29680. serializationObject.uvs5 = this.uvs5;
  29681. }
  29682. if (this.uvs6) {
  29683. serializationObject.uvs6 = this.uvs6;
  29684. }
  29685. if (this.colors) {
  29686. serializationObject.colors = this.colors;
  29687. }
  29688. if (this.matricesIndices) {
  29689. serializationObject.matricesIndices = this.matricesIndices;
  29690. serializationObject.matricesIndices._isExpanded = true;
  29691. }
  29692. if (this.matricesWeights) {
  29693. serializationObject.matricesWeights = this.matricesWeights;
  29694. }
  29695. if (this.matricesIndicesExtra) {
  29696. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29697. serializationObject.matricesIndicesExtra._isExpanded = true;
  29698. }
  29699. if (this.matricesWeightsExtra) {
  29700. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29701. }
  29702. serializationObject.indices = this.indices;
  29703. return serializationObject;
  29704. };
  29705. // Statics
  29706. /**
  29707. * Returns the object VertexData associated to the passed mesh.
  29708. */
  29709. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29710. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29711. };
  29712. /**
  29713. * Returns the object VertexData associated to the passed geometry.
  29714. */
  29715. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29716. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29717. };
  29718. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29719. var result = new VertexData();
  29720. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29721. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29722. }
  29723. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29724. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29725. }
  29726. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29727. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29728. }
  29729. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29730. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29731. }
  29732. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29733. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29734. }
  29735. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29736. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29737. }
  29738. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29739. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29740. }
  29741. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29742. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29743. }
  29744. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29745. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29746. }
  29747. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29748. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29749. }
  29750. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29751. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29752. }
  29753. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29754. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29755. }
  29756. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29757. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29758. }
  29759. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29760. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29761. }
  29762. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29763. return result;
  29764. };
  29765. /**
  29766. * Creates the vertexData of the Ribbon.
  29767. */
  29768. VertexData.CreateRibbon = function (options) {
  29769. var pathArray = options.pathArray;
  29770. var closeArray = options.closeArray || false;
  29771. var closePath = options.closePath || false;
  29772. var invertUV = options.invertUV || false;
  29773. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29774. var offset = options.offset || defaultOffset;
  29775. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29776. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29777. var customUV = options.uvs;
  29778. var customColors = options.colors;
  29779. var positions = [];
  29780. var indices = [];
  29781. var normals = [];
  29782. var uvs = [];
  29783. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29784. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29785. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29786. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29787. var minlg; // minimal length among all paths from pathArray
  29788. var lg = []; // array of path lengths : nb of vertex per path
  29789. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29790. var p; // path iterator
  29791. var i; // point iterator
  29792. var j; // point iterator
  29793. // if single path in pathArray
  29794. if (pathArray.length < 2) {
  29795. var ar1 = [];
  29796. var ar2 = [];
  29797. for (i = 0; i < pathArray[0].length - offset; i++) {
  29798. ar1.push(pathArray[0][i]);
  29799. ar2.push(pathArray[0][i + offset]);
  29800. }
  29801. pathArray = [ar1, ar2];
  29802. }
  29803. // positions and horizontal distances (u)
  29804. var idc = 0;
  29805. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29806. var path;
  29807. var l;
  29808. minlg = pathArray[0].length;
  29809. var vectlg;
  29810. var dist;
  29811. for (p = 0; p < pathArray.length; p++) {
  29812. uTotalDistance[p] = 0;
  29813. us[p] = [0];
  29814. path = pathArray[p];
  29815. l = path.length;
  29816. minlg = (minlg < l) ? minlg : l;
  29817. j = 0;
  29818. while (j < l) {
  29819. positions.push(path[j].x, path[j].y, path[j].z);
  29820. if (j > 0) {
  29821. vectlg = path[j].subtract(path[j - 1]).length();
  29822. dist = vectlg + uTotalDistance[p];
  29823. us[p].push(dist);
  29824. uTotalDistance[p] = dist;
  29825. }
  29826. j++;
  29827. }
  29828. if (closePath) {
  29829. j--;
  29830. positions.push(path[0].x, path[0].y, path[0].z);
  29831. vectlg = path[j].subtract(path[0]).length();
  29832. dist = vectlg + uTotalDistance[p];
  29833. us[p].push(dist);
  29834. uTotalDistance[p] = dist;
  29835. }
  29836. lg[p] = l + closePathCorr;
  29837. idx[p] = idc;
  29838. idc += (l + closePathCorr);
  29839. }
  29840. // vertical distances (v)
  29841. var path1;
  29842. var path2;
  29843. var vertex1 = null;
  29844. var vertex2 = null;
  29845. for (i = 0; i < minlg + closePathCorr; i++) {
  29846. vTotalDistance[i] = 0;
  29847. vs[i] = [0];
  29848. for (p = 0; p < pathArray.length - 1; p++) {
  29849. path1 = pathArray[p];
  29850. path2 = pathArray[p + 1];
  29851. if (i === minlg) {
  29852. vertex1 = path1[0];
  29853. vertex2 = path2[0];
  29854. }
  29855. else {
  29856. vertex1 = path1[i];
  29857. vertex2 = path2[i];
  29858. }
  29859. vectlg = vertex2.subtract(vertex1).length();
  29860. dist = vectlg + vTotalDistance[i];
  29861. vs[i].push(dist);
  29862. vTotalDistance[i] = dist;
  29863. }
  29864. if (closeArray && vertex2 && vertex1) {
  29865. path1 = pathArray[p];
  29866. path2 = pathArray[0];
  29867. if (i === minlg) {
  29868. vertex2 = path2[0];
  29869. }
  29870. vectlg = vertex2.subtract(vertex1).length();
  29871. dist = vectlg + vTotalDistance[i];
  29872. vTotalDistance[i] = dist;
  29873. }
  29874. }
  29875. // uvs
  29876. var u;
  29877. var v;
  29878. if (customUV) {
  29879. for (p = 0; p < customUV.length; p++) {
  29880. uvs.push(customUV[p].x, customUV[p].y);
  29881. }
  29882. }
  29883. else {
  29884. for (p = 0; p < pathArray.length; p++) {
  29885. for (i = 0; i < minlg + closePathCorr; i++) {
  29886. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29887. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29888. if (invertUV) {
  29889. uvs.push(v, u);
  29890. }
  29891. else {
  29892. uvs.push(u, v);
  29893. }
  29894. }
  29895. }
  29896. }
  29897. // indices
  29898. p = 0; // path index
  29899. var pi = 0; // positions array index
  29900. var l1 = lg[p] - 1; // path1 length
  29901. var l2 = lg[p + 1] - 1; // path2 length
  29902. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29903. var shft = idx[1] - idx[0]; // shift
  29904. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29905. while (pi <= min && p < path1nb) {
  29906. // 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
  29907. indices.push(pi, pi + shft, pi + 1);
  29908. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29909. pi += 1;
  29910. if (pi === min) {
  29911. p++;
  29912. if (p === lg.length - 1) {
  29913. shft = idx[0] - idx[p];
  29914. l1 = lg[p] - 1;
  29915. l2 = lg[0] - 1;
  29916. }
  29917. else {
  29918. shft = idx[p + 1] - idx[p];
  29919. l1 = lg[p] - 1;
  29920. l2 = lg[p + 1] - 1;
  29921. }
  29922. pi = idx[p];
  29923. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29924. }
  29925. }
  29926. // normals
  29927. VertexData.ComputeNormals(positions, indices, normals);
  29928. if (closePath) {
  29929. var indexFirst = 0;
  29930. var indexLast = 0;
  29931. for (p = 0; p < pathArray.length; p++) {
  29932. indexFirst = idx[p] * 3;
  29933. if (p + 1 < pathArray.length) {
  29934. indexLast = (idx[p + 1] - 1) * 3;
  29935. }
  29936. else {
  29937. indexLast = normals.length - 3;
  29938. }
  29939. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29940. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29941. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29942. normals[indexLast] = normals[indexFirst];
  29943. normals[indexLast + 1] = normals[indexFirst + 1];
  29944. normals[indexLast + 2] = normals[indexFirst + 2];
  29945. }
  29946. }
  29947. // sides
  29948. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29949. // Colors
  29950. var colors = null;
  29951. if (customColors) {
  29952. colors = new Float32Array(customColors.length * 4);
  29953. for (var c = 0; c < customColors.length; c++) {
  29954. colors[c * 4] = customColors[c].r;
  29955. colors[c * 4 + 1] = customColors[c].g;
  29956. colors[c * 4 + 2] = customColors[c].b;
  29957. colors[c * 4 + 3] = customColors[c].a;
  29958. }
  29959. }
  29960. // Result
  29961. var vertexData = new VertexData();
  29962. var positions32 = new Float32Array(positions);
  29963. var normals32 = new Float32Array(normals);
  29964. var uvs32 = new Float32Array(uvs);
  29965. vertexData.indices = indices;
  29966. vertexData.positions = positions32;
  29967. vertexData.normals = normals32;
  29968. vertexData.uvs = uvs32;
  29969. if (colors) {
  29970. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29971. }
  29972. if (closePath) {
  29973. vertexData._idx = idx;
  29974. }
  29975. return vertexData;
  29976. };
  29977. /**
  29978. * Creates the VertexData of the Box.
  29979. */
  29980. VertexData.CreateBox = function (options) {
  29981. var normalsSource = [
  29982. new BABYLON.Vector3(0, 0, 1),
  29983. new BABYLON.Vector3(0, 0, -1),
  29984. new BABYLON.Vector3(1, 0, 0),
  29985. new BABYLON.Vector3(-1, 0, 0),
  29986. new BABYLON.Vector3(0, 1, 0),
  29987. new BABYLON.Vector3(0, -1, 0)
  29988. ];
  29989. var indices = [];
  29990. var positions = [];
  29991. var normals = [];
  29992. var uvs = [];
  29993. var width = options.width || options.size || 1;
  29994. var height = options.height || options.size || 1;
  29995. var depth = options.depth || options.size || 1;
  29996. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29997. var faceUV = options.faceUV || new Array(6);
  29998. var faceColors = options.faceColors;
  29999. var colors = [];
  30000. // default face colors and UV if undefined
  30001. for (var f = 0; f < 6; f++) {
  30002. if (faceUV[f] === undefined) {
  30003. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30004. }
  30005. if (faceColors && faceColors[f] === undefined) {
  30006. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30007. }
  30008. }
  30009. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30010. // Create each face in turn.
  30011. for (var index = 0; index < normalsSource.length; index++) {
  30012. var normal = normalsSource[index];
  30013. // Get two vectors perpendicular to the face normal and to each other.
  30014. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30015. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30016. // Six indices (two triangles) per face.
  30017. var verticesLength = positions.length / 3;
  30018. indices.push(verticesLength);
  30019. indices.push(verticesLength + 1);
  30020. indices.push(verticesLength + 2);
  30021. indices.push(verticesLength);
  30022. indices.push(verticesLength + 2);
  30023. indices.push(verticesLength + 3);
  30024. // Four vertices per face.
  30025. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30026. positions.push(vertex.x, vertex.y, vertex.z);
  30027. normals.push(normal.x, normal.y, normal.z);
  30028. uvs.push(faceUV[index].z, faceUV[index].w);
  30029. if (faceColors) {
  30030. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30031. }
  30032. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30033. positions.push(vertex.x, vertex.y, vertex.z);
  30034. normals.push(normal.x, normal.y, normal.z);
  30035. uvs.push(faceUV[index].x, faceUV[index].w);
  30036. if (faceColors) {
  30037. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30038. }
  30039. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30040. positions.push(vertex.x, vertex.y, vertex.z);
  30041. normals.push(normal.x, normal.y, normal.z);
  30042. uvs.push(faceUV[index].x, faceUV[index].y);
  30043. if (faceColors) {
  30044. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30045. }
  30046. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30047. positions.push(vertex.x, vertex.y, vertex.z);
  30048. normals.push(normal.x, normal.y, normal.z);
  30049. uvs.push(faceUV[index].z, faceUV[index].y);
  30050. if (faceColors) {
  30051. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30052. }
  30053. }
  30054. // sides
  30055. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30056. // Result
  30057. var vertexData = new VertexData();
  30058. vertexData.indices = indices;
  30059. vertexData.positions = positions;
  30060. vertexData.normals = normals;
  30061. vertexData.uvs = uvs;
  30062. if (faceColors) {
  30063. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30064. vertexData.colors = totalColors;
  30065. }
  30066. return vertexData;
  30067. };
  30068. /**
  30069. * Creates the VertexData of the Sphere.
  30070. */
  30071. VertexData.CreateSphere = function (options) {
  30072. var segments = options.segments || 32;
  30073. var diameterX = options.diameterX || options.diameter || 1;
  30074. var diameterY = options.diameterY || options.diameter || 1;
  30075. var diameterZ = options.diameterZ || options.diameter || 1;
  30076. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30077. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30078. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30079. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30080. var totalZRotationSteps = 2 + segments;
  30081. var totalYRotationSteps = 2 * totalZRotationSteps;
  30082. var indices = [];
  30083. var positions = [];
  30084. var normals = [];
  30085. var uvs = [];
  30086. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30087. var normalizedZ = zRotationStep / totalZRotationSteps;
  30088. var angleZ = normalizedZ * Math.PI * slice;
  30089. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30090. var normalizedY = yRotationStep / totalYRotationSteps;
  30091. var angleY = normalizedY * Math.PI * 2 * arc;
  30092. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30093. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30094. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30095. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30096. var vertex = complete.multiply(radius);
  30097. var normal = complete.divide(radius).normalize();
  30098. positions.push(vertex.x, vertex.y, vertex.z);
  30099. normals.push(normal.x, normal.y, normal.z);
  30100. uvs.push(normalizedY, normalizedZ);
  30101. }
  30102. if (zRotationStep > 0) {
  30103. var verticesCount = positions.length / 3;
  30104. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30105. indices.push((firstIndex));
  30106. indices.push((firstIndex + 1));
  30107. indices.push(firstIndex + totalYRotationSteps + 1);
  30108. indices.push((firstIndex + totalYRotationSteps + 1));
  30109. indices.push((firstIndex + 1));
  30110. indices.push((firstIndex + totalYRotationSteps + 2));
  30111. }
  30112. }
  30113. }
  30114. // Sides
  30115. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30116. // Result
  30117. var vertexData = new VertexData();
  30118. vertexData.indices = indices;
  30119. vertexData.positions = positions;
  30120. vertexData.normals = normals;
  30121. vertexData.uvs = uvs;
  30122. return vertexData;
  30123. };
  30124. /**
  30125. * Creates the VertexData of the Cylinder or Cone.
  30126. */
  30127. VertexData.CreateCylinder = function (options) {
  30128. var height = options.height || 2;
  30129. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30130. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  30131. var tessellation = options.tessellation || 24;
  30132. var subdivisions = options.subdivisions || 1;
  30133. var hasRings = options.hasRings ? true : false;
  30134. var enclose = options.enclose ? true : false;
  30135. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30136. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30137. var faceUV = options.faceUV || new Array(3);
  30138. var faceColors = options.faceColors;
  30139. // default face colors and UV if undefined
  30140. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30141. var ringNb = (hasRings) ? subdivisions : 1;
  30142. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30143. var f;
  30144. for (f = 0; f < surfaceNb; f++) {
  30145. if (faceColors && faceColors[f] === undefined) {
  30146. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30147. }
  30148. }
  30149. for (f = 0; f < surfaceNb; f++) {
  30150. if (faceUV && faceUV[f] === undefined) {
  30151. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30152. }
  30153. }
  30154. var indices = new Array();
  30155. var positions = new Array();
  30156. var normals = new Array();
  30157. var uvs = new Array();
  30158. var colors = new Array();
  30159. var angle_step = Math.PI * 2 * arc / tessellation;
  30160. var angle;
  30161. var h;
  30162. var radius;
  30163. var tan = (diameterBottom - diameterTop) / 2 / height;
  30164. var ringVertex = BABYLON.Vector3.Zero();
  30165. var ringNormal = BABYLON.Vector3.Zero();
  30166. var ringFirstVertex = BABYLON.Vector3.Zero();
  30167. var ringFirstNormal = BABYLON.Vector3.Zero();
  30168. var quadNormal = BABYLON.Vector3.Zero();
  30169. var Y = BABYLON.Axis.Y;
  30170. // positions, normals, uvs
  30171. var i;
  30172. var j;
  30173. var r;
  30174. var ringIdx = 1;
  30175. var s = 1; // surface index
  30176. var cs = 0;
  30177. var v = 0;
  30178. for (i = 0; i <= subdivisions; i++) {
  30179. h = i / subdivisions;
  30180. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30181. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30182. for (r = 0; r < ringIdx; r++) {
  30183. if (hasRings) {
  30184. s += r;
  30185. }
  30186. if (enclose) {
  30187. s += 2 * r;
  30188. }
  30189. for (j = 0; j <= tessellation; j++) {
  30190. angle = j * angle_step;
  30191. // position
  30192. ringVertex.x = Math.cos(-angle) * radius;
  30193. ringVertex.y = -height / 2 + h * height;
  30194. ringVertex.z = Math.sin(-angle) * radius;
  30195. // normal
  30196. if (diameterTop === 0 && i === subdivisions) {
  30197. // if no top cap, reuse former normals
  30198. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30199. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30200. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30201. }
  30202. else {
  30203. ringNormal.x = ringVertex.x;
  30204. ringNormal.z = ringVertex.z;
  30205. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30206. ringNormal.normalize();
  30207. }
  30208. // keep first ring vertex values for enclose
  30209. if (j === 0) {
  30210. ringFirstVertex.copyFrom(ringVertex);
  30211. ringFirstNormal.copyFrom(ringNormal);
  30212. }
  30213. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30214. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30215. if (hasRings) {
  30216. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30217. }
  30218. else {
  30219. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30220. }
  30221. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30222. if (faceColors) {
  30223. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30224. }
  30225. }
  30226. // if enclose, add four vertices and their dedicated normals
  30227. if (arc !== 1 && enclose) {
  30228. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30229. positions.push(0, ringVertex.y, 0);
  30230. positions.push(0, ringVertex.y, 0);
  30231. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30232. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30233. quadNormal.normalize();
  30234. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30235. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30236. quadNormal.normalize();
  30237. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30238. if (hasRings) {
  30239. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30240. }
  30241. else {
  30242. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30243. }
  30244. uvs.push(faceUV[s + 1].x, v);
  30245. uvs.push(faceUV[s + 1].z, v);
  30246. if (hasRings) {
  30247. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30248. }
  30249. else {
  30250. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30251. }
  30252. uvs.push(faceUV[s + 2].x, v);
  30253. uvs.push(faceUV[s + 2].z, v);
  30254. if (faceColors) {
  30255. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30256. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30257. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30258. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30259. }
  30260. }
  30261. if (cs !== s) {
  30262. cs = s;
  30263. }
  30264. }
  30265. }
  30266. // indices
  30267. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30268. var s;
  30269. i = 0;
  30270. for (s = 0; s < subdivisions; s++) {
  30271. var i0 = 0;
  30272. var i1 = 0;
  30273. var i2 = 0;
  30274. var i3 = 0;
  30275. for (j = 0; j < tessellation; j++) {
  30276. i0 = i * (e + 1) + j;
  30277. i1 = (i + 1) * (e + 1) + j;
  30278. i2 = i * (e + 1) + (j + 1);
  30279. i3 = (i + 1) * (e + 1) + (j + 1);
  30280. indices.push(i0, i1, i2);
  30281. indices.push(i3, i2, i1);
  30282. }
  30283. if (arc !== 1 && enclose) {
  30284. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30285. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30286. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30287. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30288. }
  30289. i = (hasRings) ? (i + 2) : (i + 1);
  30290. }
  30291. // Caps
  30292. var createCylinderCap = function (isTop) {
  30293. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30294. if (radius === 0) {
  30295. return;
  30296. }
  30297. // Cap positions, normals & uvs
  30298. var angle;
  30299. var circleVector;
  30300. var i;
  30301. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30302. var c = null;
  30303. if (faceColors) {
  30304. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30305. }
  30306. // cap center
  30307. var vbase = positions.length / 3;
  30308. var offset = isTop ? height / 2 : -height / 2;
  30309. var center = new BABYLON.Vector3(0, offset, 0);
  30310. positions.push(center.x, center.y, center.z);
  30311. normals.push(0, isTop ? 1 : -1, 0);
  30312. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30313. if (c) {
  30314. colors.push(c.r, c.g, c.b, c.a);
  30315. }
  30316. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30317. for (i = 0; i <= tessellation; i++) {
  30318. angle = Math.PI * 2 * i * arc / tessellation;
  30319. var cos = Math.cos(-angle);
  30320. var sin = Math.sin(-angle);
  30321. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30322. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30323. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30324. normals.push(0, isTop ? 1 : -1, 0);
  30325. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30326. if (c) {
  30327. colors.push(c.r, c.g, c.b, c.a);
  30328. }
  30329. }
  30330. // Cap indices
  30331. for (i = 0; i < tessellation; i++) {
  30332. if (!isTop) {
  30333. indices.push(vbase);
  30334. indices.push(vbase + (i + 1));
  30335. indices.push(vbase + (i + 2));
  30336. }
  30337. else {
  30338. indices.push(vbase);
  30339. indices.push(vbase + (i + 2));
  30340. indices.push(vbase + (i + 1));
  30341. }
  30342. }
  30343. };
  30344. // add caps to geometry
  30345. createCylinderCap(false);
  30346. createCylinderCap(true);
  30347. // Sides
  30348. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30349. var vertexData = new VertexData();
  30350. vertexData.indices = indices;
  30351. vertexData.positions = positions;
  30352. vertexData.normals = normals;
  30353. vertexData.uvs = uvs;
  30354. if (faceColors) {
  30355. vertexData.colors = colors;
  30356. }
  30357. return vertexData;
  30358. };
  30359. /**
  30360. * Creates the VertexData of the Torus.
  30361. */
  30362. VertexData.CreateTorus = function (options) {
  30363. var indices = [];
  30364. var positions = [];
  30365. var normals = [];
  30366. var uvs = [];
  30367. var diameter = options.diameter || 1;
  30368. var thickness = options.thickness || 0.5;
  30369. var tessellation = options.tessellation || 16;
  30370. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30371. var stride = tessellation + 1;
  30372. for (var i = 0; i <= tessellation; i++) {
  30373. var u = i / tessellation;
  30374. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30375. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30376. for (var j = 0; j <= tessellation; j++) {
  30377. var v = 1 - j / tessellation;
  30378. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30379. var dx = Math.cos(innerAngle);
  30380. var dy = Math.sin(innerAngle);
  30381. // Create a vertex.
  30382. var normal = new BABYLON.Vector3(dx, dy, 0);
  30383. var position = normal.scale(thickness / 2);
  30384. var textureCoordinate = new BABYLON.Vector2(u, v);
  30385. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30386. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30387. positions.push(position.x, position.y, position.z);
  30388. normals.push(normal.x, normal.y, normal.z);
  30389. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30390. // And create indices for two triangles.
  30391. var nextI = (i + 1) % stride;
  30392. var nextJ = (j + 1) % stride;
  30393. indices.push(i * stride + j);
  30394. indices.push(i * stride + nextJ);
  30395. indices.push(nextI * stride + j);
  30396. indices.push(i * stride + nextJ);
  30397. indices.push(nextI * stride + nextJ);
  30398. indices.push(nextI * stride + j);
  30399. }
  30400. }
  30401. // Sides
  30402. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30403. // Result
  30404. var vertexData = new VertexData();
  30405. vertexData.indices = indices;
  30406. vertexData.positions = positions;
  30407. vertexData.normals = normals;
  30408. vertexData.uvs = uvs;
  30409. return vertexData;
  30410. };
  30411. /**
  30412. * Creates the VertexData of the LineSystem.
  30413. */
  30414. VertexData.CreateLineSystem = function (options) {
  30415. var indices = [];
  30416. var positions = [];
  30417. var lines = options.lines;
  30418. var colors = options.colors;
  30419. var vertexColors = [];
  30420. var idx = 0;
  30421. for (var l = 0; l < lines.length; l++) {
  30422. var points = lines[l];
  30423. for (var index = 0; index < points.length; index++) {
  30424. positions.push(points[index].x, points[index].y, points[index].z);
  30425. if (colors) {
  30426. var color = colors[l];
  30427. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  30428. }
  30429. if (index > 0) {
  30430. indices.push(idx - 1);
  30431. indices.push(idx);
  30432. }
  30433. idx++;
  30434. }
  30435. }
  30436. var vertexData = new VertexData();
  30437. vertexData.indices = indices;
  30438. vertexData.positions = positions;
  30439. if (colors) {
  30440. vertexData.colors = vertexColors;
  30441. }
  30442. return vertexData;
  30443. };
  30444. /**
  30445. * Create the VertexData of the DashedLines.
  30446. */
  30447. VertexData.CreateDashedLines = function (options) {
  30448. var dashSize = options.dashSize || 3;
  30449. var gapSize = options.gapSize || 1;
  30450. var dashNb = options.dashNb || 200;
  30451. var points = options.points;
  30452. var positions = new Array();
  30453. var indices = new Array();
  30454. var curvect = BABYLON.Vector3.Zero();
  30455. var lg = 0;
  30456. var nb = 0;
  30457. var shft = 0;
  30458. var dashshft = 0;
  30459. var curshft = 0;
  30460. var idx = 0;
  30461. var i = 0;
  30462. for (i = 0; i < points.length - 1; i++) {
  30463. points[i + 1].subtractToRef(points[i], curvect);
  30464. lg += curvect.length();
  30465. }
  30466. shft = lg / dashNb;
  30467. dashshft = dashSize * shft / (dashSize + gapSize);
  30468. for (i = 0; i < points.length - 1; i++) {
  30469. points[i + 1].subtractToRef(points[i], curvect);
  30470. nb = Math.floor(curvect.length() / shft);
  30471. curvect.normalize();
  30472. for (var j = 0; j < nb; j++) {
  30473. curshft = shft * j;
  30474. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30475. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30476. indices.push(idx, idx + 1);
  30477. idx += 2;
  30478. }
  30479. }
  30480. // Result
  30481. var vertexData = new VertexData();
  30482. vertexData.positions = positions;
  30483. vertexData.indices = indices;
  30484. return vertexData;
  30485. };
  30486. /**
  30487. * Creates the VertexData of the Ground.
  30488. */
  30489. VertexData.CreateGround = function (options) {
  30490. var indices = [];
  30491. var positions = [];
  30492. var normals = [];
  30493. var uvs = [];
  30494. var row, col;
  30495. var width = options.width || 1;
  30496. var height = options.height || 1;
  30497. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  30498. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  30499. for (row = 0; row <= subdivisionsY; row++) {
  30500. for (col = 0; col <= subdivisionsX; col++) {
  30501. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  30502. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30503. positions.push(position.x, position.y, position.z);
  30504. normals.push(normal.x, normal.y, normal.z);
  30505. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  30506. }
  30507. }
  30508. for (row = 0; row < subdivisionsY; row++) {
  30509. for (col = 0; col < subdivisionsX; col++) {
  30510. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30511. indices.push(col + 1 + row * (subdivisionsX + 1));
  30512. indices.push(col + row * (subdivisionsX + 1));
  30513. indices.push(col + (row + 1) * (subdivisionsX + 1));
  30514. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30515. indices.push(col + row * (subdivisionsX + 1));
  30516. }
  30517. }
  30518. // Result
  30519. var vertexData = new VertexData();
  30520. vertexData.indices = indices;
  30521. vertexData.positions = positions;
  30522. vertexData.normals = normals;
  30523. vertexData.uvs = uvs;
  30524. return vertexData;
  30525. };
  30526. /**
  30527. * Creates the VertexData of the TiledGround.
  30528. */
  30529. VertexData.CreateTiledGround = function (options) {
  30530. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  30531. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  30532. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  30533. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  30534. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30535. var precision = options.precision || { w: 1, h: 1 };
  30536. var indices = new Array();
  30537. var positions = new Array();
  30538. var normals = new Array();
  30539. var uvs = new Array();
  30540. var row, col, tileRow, tileCol;
  30541. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30542. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30543. precision.w = (precision.w < 1) ? 1 : precision.w;
  30544. precision.h = (precision.h < 1) ? 1 : precision.h;
  30545. var tileSize = {
  30546. 'w': (xmax - xmin) / subdivisions.w,
  30547. 'h': (zmax - zmin) / subdivisions.h
  30548. };
  30549. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30550. // Indices
  30551. var base = positions.length / 3;
  30552. var rowLength = precision.w + 1;
  30553. for (row = 0; row < precision.h; row++) {
  30554. for (col = 0; col < precision.w; col++) {
  30555. var square = [
  30556. base + col + row * rowLength,
  30557. base + (col + 1) + row * rowLength,
  30558. base + (col + 1) + (row + 1) * rowLength,
  30559. base + col + (row + 1) * rowLength
  30560. ];
  30561. indices.push(square[1]);
  30562. indices.push(square[2]);
  30563. indices.push(square[3]);
  30564. indices.push(square[0]);
  30565. indices.push(square[1]);
  30566. indices.push(square[3]);
  30567. }
  30568. }
  30569. // Position, normals and uvs
  30570. var position = BABYLON.Vector3.Zero();
  30571. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30572. for (row = 0; row <= precision.h; row++) {
  30573. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30574. for (col = 0; col <= precision.w; col++) {
  30575. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30576. position.y = 0;
  30577. positions.push(position.x, position.y, position.z);
  30578. normals.push(normal.x, normal.y, normal.z);
  30579. uvs.push(col / precision.w, row / precision.h);
  30580. }
  30581. }
  30582. }
  30583. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30584. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30585. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30586. }
  30587. }
  30588. // Result
  30589. var vertexData = new VertexData();
  30590. vertexData.indices = indices;
  30591. vertexData.positions = positions;
  30592. vertexData.normals = normals;
  30593. vertexData.uvs = uvs;
  30594. return vertexData;
  30595. };
  30596. /**
  30597. * Creates the VertexData of the Ground designed from a heightmap.
  30598. */
  30599. VertexData.CreateGroundFromHeightMap = function (options) {
  30600. var indices = [];
  30601. var positions = [];
  30602. var normals = [];
  30603. var uvs = [];
  30604. var row, col;
  30605. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  30606. // Vertices
  30607. for (row = 0; row <= options.subdivisions; row++) {
  30608. for (col = 0; col <= options.subdivisions; col++) {
  30609. 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));
  30610. // Compute height
  30611. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30612. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30613. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30614. var r = options.buffer[pos] / 255.0;
  30615. var g = options.buffer[pos + 1] / 255.0;
  30616. var b = options.buffer[pos + 2] / 255.0;
  30617. var gradient = r * filter.r + g * filter.g + b * filter.b;
  30618. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30619. // Add vertex
  30620. positions.push(position.x, position.y, position.z);
  30621. normals.push(0, 0, 0);
  30622. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30623. }
  30624. }
  30625. // Indices
  30626. for (row = 0; row < options.subdivisions; row++) {
  30627. for (col = 0; col < options.subdivisions; col++) {
  30628. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30629. indices.push(col + 1 + row * (options.subdivisions + 1));
  30630. indices.push(col + row * (options.subdivisions + 1));
  30631. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30632. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30633. indices.push(col + row * (options.subdivisions + 1));
  30634. }
  30635. }
  30636. // Normals
  30637. VertexData.ComputeNormals(positions, indices, normals);
  30638. // Result
  30639. var vertexData = new VertexData();
  30640. vertexData.indices = indices;
  30641. vertexData.positions = positions;
  30642. vertexData.normals = normals;
  30643. vertexData.uvs = uvs;
  30644. return vertexData;
  30645. };
  30646. /**
  30647. * Creates the VertexData of the Plane.
  30648. */
  30649. VertexData.CreatePlane = function (options) {
  30650. var indices = [];
  30651. var positions = [];
  30652. var normals = [];
  30653. var uvs = [];
  30654. var width = options.width || options.size || 1;
  30655. var height = options.height || options.size || 1;
  30656. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30657. // Vertices
  30658. var halfWidth = width / 2.0;
  30659. var halfHeight = height / 2.0;
  30660. positions.push(-halfWidth, -halfHeight, 0);
  30661. normals.push(0, 0, -1.0);
  30662. uvs.push(0.0, 0.0);
  30663. positions.push(halfWidth, -halfHeight, 0);
  30664. normals.push(0, 0, -1.0);
  30665. uvs.push(1.0, 0.0);
  30666. positions.push(halfWidth, halfHeight, 0);
  30667. normals.push(0, 0, -1.0);
  30668. uvs.push(1.0, 1.0);
  30669. positions.push(-halfWidth, halfHeight, 0);
  30670. normals.push(0, 0, -1.0);
  30671. uvs.push(0.0, 1.0);
  30672. // Indices
  30673. indices.push(0);
  30674. indices.push(1);
  30675. indices.push(2);
  30676. indices.push(0);
  30677. indices.push(2);
  30678. indices.push(3);
  30679. // Sides
  30680. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30681. // Result
  30682. var vertexData = new VertexData();
  30683. vertexData.indices = indices;
  30684. vertexData.positions = positions;
  30685. vertexData.normals = normals;
  30686. vertexData.uvs = uvs;
  30687. return vertexData;
  30688. };
  30689. /**
  30690. * Creates the VertexData of the Disc or regular Polygon.
  30691. */
  30692. VertexData.CreateDisc = function (options) {
  30693. var positions = new Array();
  30694. var indices = new Array();
  30695. var normals = new Array();
  30696. var uvs = new Array();
  30697. var radius = options.radius || 0.5;
  30698. var tessellation = options.tessellation || 64;
  30699. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30700. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30701. // positions and uvs
  30702. positions.push(0, 0, 0); // disc center first
  30703. uvs.push(0.5, 0.5);
  30704. var theta = Math.PI * 2 * arc;
  30705. var step = theta / tessellation;
  30706. for (var a = 0; a < theta; a += step) {
  30707. var x = Math.cos(a);
  30708. var y = Math.sin(a);
  30709. var u = (x + 1) / 2;
  30710. var v = (1 - y) / 2;
  30711. positions.push(radius * x, radius * y, 0);
  30712. uvs.push(u, v);
  30713. }
  30714. if (arc === 1) {
  30715. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30716. uvs.push(uvs[2], uvs[3]);
  30717. }
  30718. //indices
  30719. var vertexNb = positions.length / 3;
  30720. for (var i = 1; i < vertexNb - 1; i++) {
  30721. indices.push(i + 1, 0, i);
  30722. }
  30723. // result
  30724. VertexData.ComputeNormals(positions, indices, normals);
  30725. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30726. var vertexData = new VertexData();
  30727. vertexData.indices = indices;
  30728. vertexData.positions = positions;
  30729. vertexData.normals = normals;
  30730. vertexData.uvs = uvs;
  30731. return vertexData;
  30732. };
  30733. /**
  30734. * Re-creates the VertexData of the Polygon for sideOrientation.
  30735. */
  30736. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30737. var faceUV = fUV || new Array(3);
  30738. var faceColors = fColors;
  30739. var colors = [];
  30740. // default face colors and UV if undefined
  30741. for (var f = 0; f < 3; f++) {
  30742. if (faceUV[f] === undefined) {
  30743. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30744. }
  30745. if (faceColors && faceColors[f] === undefined) {
  30746. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30747. }
  30748. }
  30749. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30750. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30751. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30752. var indices = polygon.getIndices();
  30753. // set face colours and textures
  30754. var idx = 0;
  30755. var face = 0;
  30756. for (var index = 0; index < normals.length; index += 3) {
  30757. //Edge Face no. 1
  30758. if (Math.abs(normals[index + 1]) < 0.001) {
  30759. face = 1;
  30760. }
  30761. //Top Face no. 0
  30762. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30763. face = 0;
  30764. }
  30765. //Bottom Face no. 2
  30766. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30767. face = 2;
  30768. }
  30769. idx = index / 3;
  30770. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30771. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30772. if (faceColors) {
  30773. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30774. }
  30775. }
  30776. // sides
  30777. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30778. // Result
  30779. var vertexData = new VertexData();
  30780. vertexData.indices = indices;
  30781. vertexData.positions = positions;
  30782. vertexData.normals = normals;
  30783. vertexData.uvs = uvs;
  30784. if (faceColors) {
  30785. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30786. vertexData.colors = totalColors;
  30787. }
  30788. return vertexData;
  30789. };
  30790. /**
  30791. * Creates the VertexData of the IcoSphere.
  30792. */
  30793. VertexData.CreateIcoSphere = function (options) {
  30794. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30795. var radius = options.radius || 1;
  30796. var flat = (options.flat === undefined) ? true : options.flat;
  30797. var subdivisions = options.subdivisions || 4;
  30798. var radiusX = options.radiusX || radius;
  30799. var radiusY = options.radiusY || radius;
  30800. var radiusZ = options.radiusZ || radius;
  30801. var t = (1 + Math.sqrt(5)) / 2;
  30802. // 12 vertex x,y,z
  30803. var ico_vertices = [
  30804. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30805. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30806. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30807. ];
  30808. // index of 3 vertex makes a face of icopshere
  30809. var ico_indices = [
  30810. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30811. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30812. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30813. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30814. ];
  30815. // vertex for uv have aliased position, not for UV
  30816. var vertices_unalias_id = [
  30817. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30818. // vertex alias
  30819. 0,
  30820. 2,
  30821. 3,
  30822. 3,
  30823. 3,
  30824. 4,
  30825. 7,
  30826. 8,
  30827. 9,
  30828. 9,
  30829. 10,
  30830. 11 // 23: B + 12
  30831. ];
  30832. // uv as integer step (not pixels !)
  30833. var ico_vertexuv = [
  30834. 5, 1, 3, 1, 6, 4, 0, 0,
  30835. 5, 3, 4, 2, 2, 2, 4, 0,
  30836. 2, 0, 1, 1, 6, 0, 6, 2,
  30837. // vertex alias (for same vertex on different faces)
  30838. 0, 4,
  30839. 3, 3,
  30840. 4, 4,
  30841. 3, 1,
  30842. 4, 2,
  30843. 4, 4,
  30844. 0, 2,
  30845. 1, 1,
  30846. 2, 2,
  30847. 3, 3,
  30848. 1, 3,
  30849. 2, 4 // 23: B + 12
  30850. ];
  30851. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30852. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30853. // First island of uv mapping
  30854. // v = 4h 3+ 2
  30855. // v = 3h 9+ 4
  30856. // v = 2h 9+ 5 B
  30857. // v = 1h 9 1 0
  30858. // v = 0h 3 8 7 A
  30859. // u = 0 1 2 3 4 5 6 *a
  30860. // Second island of uv mapping
  30861. // v = 4h 0+ B+ 4+
  30862. // v = 3h A+ 2+
  30863. // v = 2h 7+ 6 3+
  30864. // v = 1h 8+ 3+
  30865. // v = 0h
  30866. // u = 0 1 2 3 4 5 6 *a
  30867. // Face layout on texture UV mapping
  30868. // ============
  30869. // \ 4 /\ 16 / ======
  30870. // \ / \ / /\ 11 /
  30871. // \/ 7 \/ / \ /
  30872. // ======= / 10 \/
  30873. // /\ 17 /\ =======
  30874. // / \ / \ \ 15 /\
  30875. // / 8 \/ 12 \ \ / \
  30876. // ============ \/ 6 \
  30877. // \ 18 /\ ============
  30878. // \ / \ \ 5 /\ 0 /
  30879. // \/ 13 \ \ / \ /
  30880. // ======= \/ 1 \/
  30881. // =============
  30882. // /\ 19 /\ 2 /\
  30883. // / \ / \ / \
  30884. // / 14 \/ 9 \/ 3 \
  30885. // ===================
  30886. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30887. var ustep = 138 / 1024;
  30888. var vstep = 239 / 1024;
  30889. var uoffset = 60 / 1024;
  30890. var voffset = 26 / 1024;
  30891. // Second island should have margin, not to touch the first island
  30892. // avoid any borderline artefact in pixel rounding
  30893. var island_u_offset = -40 / 1024;
  30894. var island_v_offset = +20 / 1024;
  30895. // face is either island 0 or 1 :
  30896. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30897. var island = [
  30898. 0, 0, 0, 0, 1,
  30899. 0, 0, 1, 1, 0,
  30900. 0, 0, 1, 1, 0,
  30901. 0, 1, 1, 1, 0 // 15 - 19
  30902. ];
  30903. var indices = new Array();
  30904. var positions = new Array();
  30905. var normals = new Array();
  30906. var uvs = new Array();
  30907. var current_indice = 0;
  30908. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30909. var face_vertex_pos = new Array(3);
  30910. var face_vertex_uv = new Array(3);
  30911. var v012;
  30912. for (v012 = 0; v012 < 3; v012++) {
  30913. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30914. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30915. }
  30916. // create all with normals
  30917. for (var face = 0; face < 20; face++) {
  30918. // 3 vertex per face
  30919. for (v012 = 0; v012 < 3; v012++) {
  30920. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30921. var v_id = ico_indices[3 * face + v012];
  30922. // vertex have 3D position (x,y,z)
  30923. 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]);
  30924. // Normalize to get normal, then scale to radius
  30925. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30926. // uv Coordinates from vertex ID
  30927. 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);
  30928. }
  30929. // Subdivide the face (interpolate pos, norm, uv)
  30930. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30931. // - norm is linear interpolation of vertex corner normal
  30932. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30933. // - uv is linear interpolation
  30934. //
  30935. // Topology is as below for sub-divide by 2
  30936. // vertex shown as v0,v1,v2
  30937. // interp index is i1 to progress in range [v0,v1[
  30938. // interp index is i2 to progress in range [v0,v2[
  30939. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30940. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30941. //
  30942. //
  30943. // i2 v2
  30944. // ^ ^
  30945. // / / \
  30946. // / / \
  30947. // / / \
  30948. // / / (0,1) \
  30949. // / #---------\
  30950. // / / \ (0,0)'/ \
  30951. // / / \ / \
  30952. // / / \ / \
  30953. // / / (0,0) \ / (1,0) \
  30954. // / #---------#---------\
  30955. // v0 v1
  30956. //
  30957. // --------------------> i1
  30958. //
  30959. // interp of (i1,i2):
  30960. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30961. // along i1 : lerp(x0,x1, i1/(S-i2))
  30962. //
  30963. // centroid of triangle is needed to get help normal computation
  30964. // (c1,c2) are used for centroid location
  30965. var interp_vertex = function (i1, i2, c1, c2) {
  30966. // vertex is interpolated from
  30967. // - face_vertex_pos[0..2]
  30968. // - face_vertex_uv[0..2]
  30969. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30970. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30971. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30972. pos_interp.normalize();
  30973. var vertex_normal;
  30974. if (flat) {
  30975. // in flat mode, recalculate normal as face centroid normal
  30976. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30977. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30978. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30979. }
  30980. else {
  30981. // in smooth mode, recalculate normal from each single vertex position
  30982. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30983. }
  30984. // Vertex normal need correction due to X,Y,Z radius scaling
  30985. vertex_normal.x /= radiusX;
  30986. vertex_normal.y /= radiusY;
  30987. vertex_normal.z /= radiusZ;
  30988. vertex_normal.normalize();
  30989. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30990. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30991. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30992. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30993. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30994. uvs.push(uv_interp.x, uv_interp.y);
  30995. // push each vertex has member of a face
  30996. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30997. indices.push(current_indice);
  30998. current_indice++;
  30999. };
  31000. for (var i2 = 0; i2 < subdivisions; i2++) {
  31001. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  31002. // face : (i1,i2) for /\ :
  31003. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  31004. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31005. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31006. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31007. if (i1 + i2 + 1 < subdivisions) {
  31008. // face : (i1,i2)' for \/ :
  31009. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31010. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31011. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31012. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31013. }
  31014. }
  31015. }
  31016. }
  31017. // Sides
  31018. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31019. // Result
  31020. var vertexData = new VertexData();
  31021. vertexData.indices = indices;
  31022. vertexData.positions = positions;
  31023. vertexData.normals = normals;
  31024. vertexData.uvs = uvs;
  31025. return vertexData;
  31026. };
  31027. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31028. /**
  31029. * Creates the VertexData of the Polyhedron.
  31030. */
  31031. VertexData.CreatePolyhedron = function (options) {
  31032. // provided polyhedron types :
  31033. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31034. // 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)
  31035. var polyhedra = [];
  31036. 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]] };
  31037. 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]] };
  31038. polyhedra[2] = {
  31039. 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]],
  31040. 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]]
  31041. };
  31042. polyhedra[3] = {
  31043. 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]],
  31044. 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]]
  31045. };
  31046. polyhedra[4] = {
  31047. 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]],
  31048. 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]]
  31049. };
  31050. 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]] };
  31051. 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]] };
  31052. 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]] };
  31053. 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]] };
  31054. 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]] };
  31055. 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]] };
  31056. 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]] };
  31057. 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]] };
  31058. 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]] };
  31059. polyhedra[14] = {
  31060. 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]],
  31061. 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]]
  31062. };
  31063. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31064. var size = options.size;
  31065. var sizeX = options.sizeX || size || 1;
  31066. var sizeY = options.sizeY || size || 1;
  31067. var sizeZ = options.sizeZ || size || 1;
  31068. var data = options.custom || polyhedra[type];
  31069. var nbfaces = data.face.length;
  31070. var faceUV = options.faceUV || new Array(nbfaces);
  31071. var faceColors = options.faceColors;
  31072. var flat = (options.flat === undefined) ? true : options.flat;
  31073. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31074. var positions = new Array();
  31075. var indices = new Array();
  31076. var normals = new Array();
  31077. var uvs = new Array();
  31078. var colors = new Array();
  31079. var index = 0;
  31080. var faceIdx = 0; // face cursor in the array "indexes"
  31081. var indexes = new Array();
  31082. var i = 0;
  31083. var f = 0;
  31084. var u, v, ang, x, y, tmp;
  31085. // default face colors and UV if undefined
  31086. if (flat) {
  31087. for (f = 0; f < nbfaces; f++) {
  31088. if (faceColors && faceColors[f] === undefined) {
  31089. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31090. }
  31091. if (faceUV && faceUV[f] === undefined) {
  31092. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31093. }
  31094. }
  31095. }
  31096. if (!flat) {
  31097. for (i = 0; i < data.vertex.length; i++) {
  31098. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31099. uvs.push(0, 0);
  31100. }
  31101. for (f = 0; f < nbfaces; f++) {
  31102. for (i = 0; i < data.face[f].length - 2; i++) {
  31103. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31104. }
  31105. }
  31106. }
  31107. else {
  31108. for (f = 0; f < nbfaces; f++) {
  31109. var fl = data.face[f].length; // number of vertices of the current face
  31110. ang = 2 * Math.PI / fl;
  31111. x = 0.5 * Math.tan(ang / 2);
  31112. y = 0.5;
  31113. // positions, uvs, colors
  31114. for (i = 0; i < fl; i++) {
  31115. // positions
  31116. 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);
  31117. indexes.push(index);
  31118. index++;
  31119. // uvs
  31120. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31121. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31122. uvs.push(u, v);
  31123. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31124. y = x * Math.sin(ang) + y * Math.cos(ang);
  31125. x = tmp;
  31126. // colors
  31127. if (faceColors) {
  31128. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31129. }
  31130. }
  31131. // indices from indexes
  31132. for (i = 0; i < fl - 2; i++) {
  31133. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31134. }
  31135. faceIdx += fl;
  31136. }
  31137. }
  31138. VertexData.ComputeNormals(positions, indices, normals);
  31139. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31140. var vertexData = new VertexData();
  31141. vertexData.positions = positions;
  31142. vertexData.indices = indices;
  31143. vertexData.normals = normals;
  31144. vertexData.uvs = uvs;
  31145. if (faceColors && flat) {
  31146. vertexData.colors = colors;
  31147. }
  31148. return vertexData;
  31149. };
  31150. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31151. /**
  31152. * Creates the VertexData of the Torus Knot.
  31153. */
  31154. VertexData.CreateTorusKnot = function (options) {
  31155. var indices = new Array();
  31156. var positions = new Array();
  31157. var normals = new Array();
  31158. var uvs = new Array();
  31159. var radius = options.radius || 2;
  31160. var tube = options.tube || 0.5;
  31161. var radialSegments = options.radialSegments || 32;
  31162. var tubularSegments = options.tubularSegments || 32;
  31163. var p = options.p || 2;
  31164. var q = options.q || 3;
  31165. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31166. // Helper
  31167. var getPos = function (angle) {
  31168. var cu = Math.cos(angle);
  31169. var su = Math.sin(angle);
  31170. var quOverP = q / p * angle;
  31171. var cs = Math.cos(quOverP);
  31172. var tx = radius * (2 + cs) * 0.5 * cu;
  31173. var ty = radius * (2 + cs) * su * 0.5;
  31174. var tz = radius * Math.sin(quOverP) * 0.5;
  31175. return new BABYLON.Vector3(tx, ty, tz);
  31176. };
  31177. // Vertices
  31178. var i;
  31179. var j;
  31180. for (i = 0; i <= radialSegments; i++) {
  31181. var modI = i % radialSegments;
  31182. var u = modI / radialSegments * 2 * p * Math.PI;
  31183. var p1 = getPos(u);
  31184. var p2 = getPos(u + 0.01);
  31185. var tang = p2.subtract(p1);
  31186. var n = p2.add(p1);
  31187. var bitan = BABYLON.Vector3.Cross(tang, n);
  31188. n = BABYLON.Vector3.Cross(bitan, tang);
  31189. bitan.normalize();
  31190. n.normalize();
  31191. for (j = 0; j < tubularSegments; j++) {
  31192. var modJ = j % tubularSegments;
  31193. var v = modJ / tubularSegments * 2 * Math.PI;
  31194. var cx = -tube * Math.cos(v);
  31195. var cy = tube * Math.sin(v);
  31196. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31197. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31198. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31199. uvs.push(i / radialSegments);
  31200. uvs.push(j / tubularSegments);
  31201. }
  31202. }
  31203. for (i = 0; i < radialSegments; i++) {
  31204. for (j = 0; j < tubularSegments; j++) {
  31205. var jNext = (j + 1) % tubularSegments;
  31206. var a = i * tubularSegments + j;
  31207. var b = (i + 1) * tubularSegments + j;
  31208. var c = (i + 1) * tubularSegments + jNext;
  31209. var d = i * tubularSegments + jNext;
  31210. indices.push(d);
  31211. indices.push(b);
  31212. indices.push(a);
  31213. indices.push(d);
  31214. indices.push(c);
  31215. indices.push(b);
  31216. }
  31217. }
  31218. // Normals
  31219. VertexData.ComputeNormals(positions, indices, normals);
  31220. // Sides
  31221. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31222. // Result
  31223. var vertexData = new VertexData();
  31224. vertexData.indices = indices;
  31225. vertexData.positions = positions;
  31226. vertexData.normals = normals;
  31227. vertexData.uvs = uvs;
  31228. return vertexData;
  31229. };
  31230. // Tools
  31231. /**
  31232. * @param {any} - positions (number[] or Float32Array)
  31233. * @param {any} - indices (number[] or Uint16Array)
  31234. * @param {any} - normals (number[] or Float32Array)
  31235. * options (optional) :
  31236. * facetPositions : optional array of facet positions (vector3)
  31237. * facetNormals : optional array of facet normals (vector3)
  31238. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  31239. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  31240. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  31241. * bbSize : optional bounding box size data, required for facetPartitioning computation
  31242. * bInfo : optional bounding info, required for facetPartitioning computation
  31243. * useRightHandedSystem: optional boolean to for right handed system computation
  31244. * depthSort : optional boolean to enable the facet depth sort computation
  31245. * distanceTo : optional Vector3 to compute the facet depth from this location
  31246. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  31247. */
  31248. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  31249. // temporary scalar variables
  31250. var index = 0; // facet index
  31251. var p1p2x = 0.0; // p1p2 vector x coordinate
  31252. var p1p2y = 0.0; // p1p2 vector y coordinate
  31253. var p1p2z = 0.0; // p1p2 vector z coordinate
  31254. var p3p2x = 0.0; // p3p2 vector x coordinate
  31255. var p3p2y = 0.0; // p3p2 vector y coordinate
  31256. var p3p2z = 0.0; // p3p2 vector z coordinate
  31257. var faceNormalx = 0.0; // facet normal x coordinate
  31258. var faceNormaly = 0.0; // facet normal y coordinate
  31259. var faceNormalz = 0.0; // facet normal z coordinate
  31260. var length = 0.0; // facet normal length before normalization
  31261. var v1x = 0; // vector1 x index in the positions array
  31262. var v1y = 0; // vector1 y index in the positions array
  31263. var v1z = 0; // vector1 z index in the positions array
  31264. var v2x = 0; // vector2 x index in the positions array
  31265. var v2y = 0; // vector2 y index in the positions array
  31266. var v2z = 0; // vector2 z index in the positions array
  31267. var v3x = 0; // vector3 x index in the positions array
  31268. var v3y = 0; // vector3 y index in the positions array
  31269. var v3z = 0; // vector3 z index in the positions array
  31270. var computeFacetNormals = false;
  31271. var computeFacetPositions = false;
  31272. var computeFacetPartitioning = false;
  31273. var computeDepthSort = false;
  31274. var faceNormalSign = 1;
  31275. var ratio = 0;
  31276. var distanceTo = null;
  31277. if (options) {
  31278. computeFacetNormals = (options.facetNormals) ? true : false;
  31279. computeFacetPositions = (options.facetPositions) ? true : false;
  31280. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  31281. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  31282. ratio = options.ratio || 0;
  31283. computeDepthSort = (options.depthSort) ? true : false;
  31284. distanceTo = (options.distanceTo);
  31285. if (computeDepthSort) {
  31286. if (distanceTo === undefined) {
  31287. distanceTo = BABYLON.Vector3.Zero();
  31288. }
  31289. var depthSortedFacets = options.depthSortedFacets;
  31290. }
  31291. }
  31292. // facetPartitioning reinit if needed
  31293. var xSubRatio = 0;
  31294. var ySubRatio = 0;
  31295. var zSubRatio = 0;
  31296. var subSq = 0;
  31297. if (computeFacetPartitioning && options && options.bbSize) {
  31298. var ox = 0; // X partitioning index for facet position
  31299. var oy = 0; // Y partinioning index for facet position
  31300. var oz = 0; // Z partinioning index for facet position
  31301. var b1x = 0; // X partitioning index for facet v1 vertex
  31302. var b1y = 0; // Y partitioning index for facet v1 vertex
  31303. var b1z = 0; // z partitioning index for facet v1 vertex
  31304. var b2x = 0; // X partitioning index for facet v2 vertex
  31305. var b2y = 0; // Y partitioning index for facet v2 vertex
  31306. var b2z = 0; // Z partitioning index for facet v2 vertex
  31307. var b3x = 0; // X partitioning index for facet v3 vertex
  31308. var b3y = 0; // Y partitioning index for facet v3 vertex
  31309. var b3z = 0; // Z partitioning index for facet v3 vertex
  31310. var block_idx_o = 0; // facet barycenter block index
  31311. var block_idx_v1 = 0; // v1 vertex block index
  31312. var block_idx_v2 = 0; // v2 vertex block index
  31313. var block_idx_v3 = 0; // v3 vertex block index
  31314. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  31315. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  31316. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  31317. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  31318. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  31319. subSq = options.subDiv.max * options.subDiv.max;
  31320. options.facetPartitioning.length = 0;
  31321. }
  31322. // reset the normals
  31323. for (index = 0; index < positions.length; index++) {
  31324. normals[index] = 0.0;
  31325. }
  31326. // Loop : 1 indice triplet = 1 facet
  31327. var nbFaces = (indices.length / 3) | 0;
  31328. for (index = 0; index < nbFaces; index++) {
  31329. // get the indexes of the coordinates of each vertex of the facet
  31330. v1x = indices[index * 3] * 3;
  31331. v1y = v1x + 1;
  31332. v1z = v1x + 2;
  31333. v2x = indices[index * 3 + 1] * 3;
  31334. v2y = v2x + 1;
  31335. v2z = v2x + 2;
  31336. v3x = indices[index * 3 + 2] * 3;
  31337. v3y = v3x + 1;
  31338. v3z = v3x + 2;
  31339. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  31340. p1p2y = positions[v1y] - positions[v2y];
  31341. p1p2z = positions[v1z] - positions[v2z];
  31342. p3p2x = positions[v3x] - positions[v2x];
  31343. p3p2y = positions[v3y] - positions[v2y];
  31344. p3p2z = positions[v3z] - positions[v2z];
  31345. // compute the face normal with the cross product
  31346. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  31347. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  31348. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  31349. // normalize this normal and store it in the array facetData
  31350. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31351. length = (length === 0) ? 1.0 : length;
  31352. faceNormalx /= length;
  31353. faceNormaly /= length;
  31354. faceNormalz /= length;
  31355. if (computeFacetNormals && options) {
  31356. options.facetNormals[index].x = faceNormalx;
  31357. options.facetNormals[index].y = faceNormaly;
  31358. options.facetNormals[index].z = faceNormalz;
  31359. }
  31360. if (computeFacetPositions && options) {
  31361. // compute and the facet barycenter coordinates in the array facetPositions
  31362. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  31363. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  31364. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  31365. }
  31366. if (computeFacetPartitioning && options) {
  31367. // store the facet indexes in arrays in the main facetPartitioning array :
  31368. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  31369. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  31370. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  31371. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  31372. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31373. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31374. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31375. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31376. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31377. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31378. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31379. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31380. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31381. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  31382. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  31383. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  31384. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  31385. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  31386. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  31387. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  31388. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  31389. // push each facet index in each block containing the vertex
  31390. options.facetPartitioning[block_idx_v1].push(index);
  31391. if (block_idx_v2 != block_idx_v1) {
  31392. options.facetPartitioning[block_idx_v2].push(index);
  31393. }
  31394. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  31395. options.facetPartitioning[block_idx_v3].push(index);
  31396. }
  31397. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  31398. options.facetPartitioning[block_idx_o].push(index);
  31399. }
  31400. }
  31401. if (computeDepthSort && options && options.facetPositions) {
  31402. var dsf = depthSortedFacets[index];
  31403. dsf.ind = index * 3;
  31404. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  31405. }
  31406. // compute the normals anyway
  31407. normals[v1x] += faceNormalx; // accumulate all the normals per face
  31408. normals[v1y] += faceNormaly;
  31409. normals[v1z] += faceNormalz;
  31410. normals[v2x] += faceNormalx;
  31411. normals[v2y] += faceNormaly;
  31412. normals[v2z] += faceNormalz;
  31413. normals[v3x] += faceNormalx;
  31414. normals[v3y] += faceNormaly;
  31415. normals[v3z] += faceNormalz;
  31416. }
  31417. // last normalization of each normal
  31418. for (index = 0; index < normals.length / 3; index++) {
  31419. faceNormalx = normals[index * 3];
  31420. faceNormaly = normals[index * 3 + 1];
  31421. faceNormalz = normals[index * 3 + 2];
  31422. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31423. length = (length === 0) ? 1.0 : length;
  31424. faceNormalx /= length;
  31425. faceNormaly /= length;
  31426. faceNormalz /= length;
  31427. normals[index * 3] = faceNormalx;
  31428. normals[index * 3 + 1] = faceNormaly;
  31429. normals[index * 3 + 2] = faceNormalz;
  31430. }
  31431. };
  31432. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  31433. var li = indices.length;
  31434. var ln = normals.length;
  31435. var i;
  31436. var n;
  31437. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31438. switch (sideOrientation) {
  31439. case BABYLON.Mesh.FRONTSIDE:
  31440. // nothing changed
  31441. break;
  31442. case BABYLON.Mesh.BACKSIDE:
  31443. var tmp;
  31444. // indices
  31445. for (i = 0; i < li; i += 3) {
  31446. tmp = indices[i];
  31447. indices[i] = indices[i + 2];
  31448. indices[i + 2] = tmp;
  31449. }
  31450. // normals
  31451. for (n = 0; n < ln; n++) {
  31452. normals[n] = -normals[n];
  31453. }
  31454. break;
  31455. case BABYLON.Mesh.DOUBLESIDE:
  31456. // positions
  31457. var lp = positions.length;
  31458. var l = lp / 3;
  31459. for (var p = 0; p < lp; p++) {
  31460. positions[lp + p] = positions[p];
  31461. }
  31462. // indices
  31463. for (i = 0; i < li; i += 3) {
  31464. indices[i + li] = indices[i + 2] + l;
  31465. indices[i + 1 + li] = indices[i + 1] + l;
  31466. indices[i + 2 + li] = indices[i] + l;
  31467. }
  31468. // normals
  31469. for (n = 0; n < ln; n++) {
  31470. normals[ln + n] = -normals[n];
  31471. }
  31472. // uvs
  31473. var lu = uvs.length;
  31474. var u = 0;
  31475. for (u = 0; u < lu; u++) {
  31476. uvs[u + lu] = uvs[u];
  31477. }
  31478. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31479. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31480. u = 0;
  31481. for (i = 0; i < lu / 2; i++) {
  31482. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  31483. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  31484. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  31485. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  31486. u += 2;
  31487. }
  31488. break;
  31489. }
  31490. };
  31491. /**
  31492. * Creates a new VertexData from the imported parameters.
  31493. */
  31494. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31495. var vertexData = new VertexData();
  31496. // positions
  31497. var positions = parsedVertexData.positions;
  31498. if (positions) {
  31499. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31500. }
  31501. // normals
  31502. var normals = parsedVertexData.normals;
  31503. if (normals) {
  31504. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31505. }
  31506. // tangents
  31507. var tangents = parsedVertexData.tangents;
  31508. if (tangents) {
  31509. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  31510. }
  31511. // uvs
  31512. var uvs = parsedVertexData.uvs;
  31513. if (uvs) {
  31514. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31515. }
  31516. // uv2s
  31517. var uv2s = parsedVertexData.uv2s;
  31518. if (uv2s) {
  31519. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31520. }
  31521. // uv3s
  31522. var uv3s = parsedVertexData.uv3s;
  31523. if (uv3s) {
  31524. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31525. }
  31526. // uv4s
  31527. var uv4s = parsedVertexData.uv4s;
  31528. if (uv4s) {
  31529. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31530. }
  31531. // uv5s
  31532. var uv5s = parsedVertexData.uv5s;
  31533. if (uv5s) {
  31534. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31535. }
  31536. // uv6s
  31537. var uv6s = parsedVertexData.uv6s;
  31538. if (uv6s) {
  31539. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31540. }
  31541. // colors
  31542. var colors = parsedVertexData.colors;
  31543. if (colors) {
  31544. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31545. }
  31546. // matricesIndices
  31547. var matricesIndices = parsedVertexData.matricesIndices;
  31548. if (matricesIndices) {
  31549. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31550. }
  31551. // matricesWeights
  31552. var matricesWeights = parsedVertexData.matricesWeights;
  31553. if (matricesWeights) {
  31554. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31555. }
  31556. // indices
  31557. var indices = parsedVertexData.indices;
  31558. if (indices) {
  31559. vertexData.indices = indices;
  31560. }
  31561. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31562. };
  31563. return VertexData;
  31564. }());
  31565. BABYLON.VertexData = VertexData;
  31566. })(BABYLON || (BABYLON = {}));
  31567. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  31568. var BABYLON;
  31569. (function (BABYLON) {
  31570. var Geometry = /** @class */ (function () {
  31571. function Geometry(id, scene, vertexData, updatable, mesh) {
  31572. if (updatable === void 0) { updatable = false; }
  31573. if (mesh === void 0) { mesh = null; }
  31574. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31575. this._totalVertices = 0;
  31576. this._isDisposed = false;
  31577. this._indexBufferIsUpdatable = false;
  31578. this.id = id;
  31579. this._engine = scene.getEngine();
  31580. this._meshes = [];
  31581. this._scene = scene;
  31582. //Init vertex buffer cache
  31583. this._vertexBuffers = {};
  31584. this._indices = [];
  31585. this._updatable = updatable;
  31586. // vertexData
  31587. if (vertexData) {
  31588. this.setAllVerticesData(vertexData, updatable);
  31589. }
  31590. else {
  31591. this._totalVertices = 0;
  31592. this._indices = [];
  31593. }
  31594. if (this._engine.getCaps().vertexArrayObject) {
  31595. this._vertexArrayObjects = {};
  31596. }
  31597. // applyToMesh
  31598. if (mesh) {
  31599. if (mesh.getClassName() === "LinesMesh") {
  31600. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31601. this.updateExtend();
  31602. }
  31603. this.applyToMesh(mesh);
  31604. mesh.computeWorldMatrix(true);
  31605. }
  31606. }
  31607. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31608. /**
  31609. * 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
  31610. * @returns The Bias Vector
  31611. */
  31612. get: function () {
  31613. return this._boundingBias;
  31614. },
  31615. set: function (value) {
  31616. if (this._boundingBias && this._boundingBias.equals(value)) {
  31617. return;
  31618. }
  31619. this._boundingBias = value.clone();
  31620. this.updateBoundingInfo(true, null);
  31621. },
  31622. enumerable: true,
  31623. configurable: true
  31624. });
  31625. Geometry.CreateGeometryForMesh = function (mesh) {
  31626. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  31627. geometry.applyToMesh(mesh);
  31628. return geometry;
  31629. };
  31630. Object.defineProperty(Geometry.prototype, "extend", {
  31631. get: function () {
  31632. return this._extend;
  31633. },
  31634. enumerable: true,
  31635. configurable: true
  31636. });
  31637. Geometry.prototype.getScene = function () {
  31638. return this._scene;
  31639. };
  31640. Geometry.prototype.getEngine = function () {
  31641. return this._engine;
  31642. };
  31643. Geometry.prototype.isReady = function () {
  31644. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31645. };
  31646. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  31647. get: function () {
  31648. for (var index = 0; index < this._meshes.length; index++) {
  31649. if (!this._meshes[index].doNotSerialize) {
  31650. return false;
  31651. }
  31652. }
  31653. return true;
  31654. },
  31655. enumerable: true,
  31656. configurable: true
  31657. });
  31658. Geometry.prototype._rebuild = function () {
  31659. if (this._vertexArrayObjects) {
  31660. this._vertexArrayObjects = {};
  31661. }
  31662. // Index buffer
  31663. if (this._meshes.length !== 0 && this._indices) {
  31664. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31665. }
  31666. // Vertex buffers
  31667. for (var key in this._vertexBuffers) {
  31668. var vertexBuffer = this._vertexBuffers[key];
  31669. vertexBuffer._rebuild();
  31670. }
  31671. };
  31672. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31673. vertexData.applyToGeometry(this, updatable);
  31674. this.notifyUpdate();
  31675. };
  31676. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31677. if (updatable === void 0) { updatable = false; }
  31678. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31679. this.setVerticesBuffer(buffer);
  31680. };
  31681. Geometry.prototype.removeVerticesData = function (kind) {
  31682. if (this._vertexBuffers[kind]) {
  31683. this._vertexBuffers[kind].dispose();
  31684. delete this._vertexBuffers[kind];
  31685. }
  31686. };
  31687. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31688. var kind = buffer.getKind();
  31689. if (this._vertexBuffers[kind]) {
  31690. this._vertexBuffers[kind].dispose();
  31691. }
  31692. this._vertexBuffers[kind] = buffer;
  31693. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31694. var data = buffer.getData();
  31695. var stride = buffer.getStrideSize();
  31696. this._totalVertices = data.length / stride;
  31697. this.updateExtend(data, stride);
  31698. this._resetPointsArrayCache();
  31699. var meshes = this._meshes;
  31700. var numOfMeshes = meshes.length;
  31701. for (var index = 0; index < numOfMeshes; index++) {
  31702. var mesh = meshes[index];
  31703. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31704. mesh._createGlobalSubMesh(false);
  31705. mesh.computeWorldMatrix(true);
  31706. }
  31707. }
  31708. this.notifyUpdate(kind);
  31709. if (this._vertexArrayObjects) {
  31710. this._disposeVertexArrayObjects();
  31711. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31712. }
  31713. };
  31714. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31715. var vertexBuffer = this.getVertexBuffer(kind);
  31716. if (!vertexBuffer) {
  31717. return;
  31718. }
  31719. vertexBuffer.updateDirectly(data, offset);
  31720. this.notifyUpdate(kind);
  31721. };
  31722. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31723. if (updateExtends === void 0) { updateExtends = false; }
  31724. var vertexBuffer = this.getVertexBuffer(kind);
  31725. if (!vertexBuffer) {
  31726. return;
  31727. }
  31728. vertexBuffer.update(data);
  31729. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31730. var stride = vertexBuffer.getStrideSize();
  31731. this._totalVertices = data.length / stride;
  31732. this.updateBoundingInfo(updateExtends, data);
  31733. }
  31734. this.notifyUpdate(kind);
  31735. };
  31736. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31737. if (updateExtends) {
  31738. this.updateExtend(data);
  31739. }
  31740. var meshes = this._meshes;
  31741. var numOfMeshes = meshes.length;
  31742. this._resetPointsArrayCache();
  31743. for (var index = 0; index < numOfMeshes; index++) {
  31744. var mesh = meshes[index];
  31745. if (updateExtends) {
  31746. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31747. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31748. var subMesh = mesh.subMeshes[subIndex];
  31749. subMesh.refreshBoundingInfo();
  31750. }
  31751. }
  31752. }
  31753. };
  31754. Geometry.prototype._bind = function (effect, indexToBind) {
  31755. if (!effect) {
  31756. return;
  31757. }
  31758. if (indexToBind === undefined) {
  31759. indexToBind = this._indexBuffer;
  31760. }
  31761. var vbs = this.getVertexBuffers();
  31762. if (!vbs) {
  31763. return;
  31764. }
  31765. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31766. this._engine.bindBuffers(vbs, indexToBind, effect);
  31767. return;
  31768. }
  31769. // Using VAO
  31770. if (!this._vertexArrayObjects[effect.key]) {
  31771. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31772. }
  31773. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31774. };
  31775. Geometry.prototype.getTotalVertices = function () {
  31776. if (!this.isReady()) {
  31777. return 0;
  31778. }
  31779. return this._totalVertices;
  31780. };
  31781. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31782. var vertexBuffer = this.getVertexBuffer(kind);
  31783. if (!vertexBuffer) {
  31784. return null;
  31785. }
  31786. var orig = vertexBuffer.getData();
  31787. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31788. return orig;
  31789. }
  31790. else {
  31791. var len = orig.length;
  31792. var copy = [];
  31793. for (var i = 0; i < len; i++) {
  31794. copy.push(orig[i]);
  31795. }
  31796. return copy;
  31797. }
  31798. };
  31799. /**
  31800. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31801. * Possible `kind` values :
  31802. * - BABYLON.VertexBuffer.PositionKind
  31803. * - BABYLON.VertexBuffer.UVKind
  31804. * - BABYLON.VertexBuffer.UV2Kind
  31805. * - BABYLON.VertexBuffer.UV3Kind
  31806. * - BABYLON.VertexBuffer.UV4Kind
  31807. * - BABYLON.VertexBuffer.UV5Kind
  31808. * - BABYLON.VertexBuffer.UV6Kind
  31809. * - BABYLON.VertexBuffer.ColorKind
  31810. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31811. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31812. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31813. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31814. */
  31815. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31816. var vb = this._vertexBuffers[kind];
  31817. if (!vb) {
  31818. return false;
  31819. }
  31820. return vb.isUpdatable();
  31821. };
  31822. Geometry.prototype.getVertexBuffer = function (kind) {
  31823. if (!this.isReady()) {
  31824. return null;
  31825. }
  31826. return this._vertexBuffers[kind];
  31827. };
  31828. Geometry.prototype.getVertexBuffers = function () {
  31829. if (!this.isReady()) {
  31830. return null;
  31831. }
  31832. return this._vertexBuffers;
  31833. };
  31834. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31835. if (!this._vertexBuffers) {
  31836. if (this._delayInfo) {
  31837. return this._delayInfo.indexOf(kind) !== -1;
  31838. }
  31839. return false;
  31840. }
  31841. return this._vertexBuffers[kind] !== undefined;
  31842. };
  31843. Geometry.prototype.getVerticesDataKinds = function () {
  31844. var result = [];
  31845. var kind;
  31846. if (!this._vertexBuffers && this._delayInfo) {
  31847. for (kind in this._delayInfo) {
  31848. result.push(kind);
  31849. }
  31850. }
  31851. else {
  31852. for (kind in this._vertexBuffers) {
  31853. result.push(kind);
  31854. }
  31855. }
  31856. return result;
  31857. };
  31858. Geometry.prototype.updateIndices = function (indices, offset) {
  31859. if (!this._indexBuffer) {
  31860. return;
  31861. }
  31862. if (!this._indexBufferIsUpdatable) {
  31863. this.setIndices(indices, null, true);
  31864. }
  31865. else {
  31866. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31867. }
  31868. };
  31869. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31870. if (totalVertices === void 0) { totalVertices = null; }
  31871. if (updatable === void 0) { updatable = false; }
  31872. if (this._indexBuffer) {
  31873. this._engine._releaseBuffer(this._indexBuffer);
  31874. }
  31875. this._disposeVertexArrayObjects();
  31876. this._indices = indices;
  31877. this._indexBufferIsUpdatable = updatable;
  31878. if (this._meshes.length !== 0 && this._indices) {
  31879. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31880. }
  31881. if (totalVertices != undefined) {
  31882. this._totalVertices = totalVertices;
  31883. }
  31884. var meshes = this._meshes;
  31885. var numOfMeshes = meshes.length;
  31886. for (var index = 0; index < numOfMeshes; index++) {
  31887. meshes[index]._createGlobalSubMesh(true);
  31888. }
  31889. this.notifyUpdate();
  31890. };
  31891. Geometry.prototype.getTotalIndices = function () {
  31892. if (!this.isReady()) {
  31893. return 0;
  31894. }
  31895. return this._indices.length;
  31896. };
  31897. Geometry.prototype.getIndices = function (copyWhenShared) {
  31898. if (!this.isReady()) {
  31899. return null;
  31900. }
  31901. var orig = this._indices;
  31902. if (!copyWhenShared || this._meshes.length === 1) {
  31903. return orig;
  31904. }
  31905. else {
  31906. var len = orig.length;
  31907. var copy = [];
  31908. for (var i = 0; i < len; i++) {
  31909. copy.push(orig[i]);
  31910. }
  31911. return copy;
  31912. }
  31913. };
  31914. Geometry.prototype.getIndexBuffer = function () {
  31915. if (!this.isReady()) {
  31916. return null;
  31917. }
  31918. return this._indexBuffer;
  31919. };
  31920. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31921. if (effect === void 0) { effect = null; }
  31922. if (!effect || !this._vertexArrayObjects) {
  31923. return;
  31924. }
  31925. if (this._vertexArrayObjects[effect.key]) {
  31926. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31927. delete this._vertexArrayObjects[effect.key];
  31928. }
  31929. };
  31930. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31931. var meshes = this._meshes;
  31932. var index = meshes.indexOf(mesh);
  31933. if (index === -1) {
  31934. return;
  31935. }
  31936. meshes.splice(index, 1);
  31937. mesh._geometry = null;
  31938. if (meshes.length === 0 && shouldDispose) {
  31939. this.dispose();
  31940. }
  31941. };
  31942. Geometry.prototype.applyToMesh = function (mesh) {
  31943. if (mesh._geometry === this) {
  31944. return;
  31945. }
  31946. var previousGeometry = mesh._geometry;
  31947. if (previousGeometry) {
  31948. previousGeometry.releaseForMesh(mesh);
  31949. }
  31950. var meshes = this._meshes;
  31951. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31952. mesh._geometry = this;
  31953. this._scene.pushGeometry(this);
  31954. meshes.push(mesh);
  31955. if (this.isReady()) {
  31956. this._applyToMesh(mesh);
  31957. }
  31958. else {
  31959. mesh._boundingInfo = this._boundingInfo;
  31960. }
  31961. };
  31962. Geometry.prototype.updateExtend = function (data, stride) {
  31963. if (data === void 0) { data = null; }
  31964. if (!data) {
  31965. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31966. }
  31967. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31968. };
  31969. Geometry.prototype._applyToMesh = function (mesh) {
  31970. var numOfMeshes = this._meshes.length;
  31971. // vertexBuffers
  31972. for (var kind in this._vertexBuffers) {
  31973. if (numOfMeshes === 1) {
  31974. this._vertexBuffers[kind].create();
  31975. }
  31976. var buffer = this._vertexBuffers[kind].getBuffer();
  31977. if (buffer)
  31978. buffer.references = numOfMeshes;
  31979. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31980. if (!this._extend) {
  31981. this.updateExtend(this._vertexBuffers[kind].getData());
  31982. }
  31983. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31984. mesh._createGlobalSubMesh(false);
  31985. //bounding info was just created again, world matrix should be applied again.
  31986. mesh._updateBoundingInfo();
  31987. }
  31988. }
  31989. // indexBuffer
  31990. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31991. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31992. }
  31993. if (this._indexBuffer) {
  31994. this._indexBuffer.references = numOfMeshes;
  31995. }
  31996. };
  31997. Geometry.prototype.notifyUpdate = function (kind) {
  31998. if (this.onGeometryUpdated) {
  31999. this.onGeometryUpdated(this, kind);
  32000. }
  32001. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  32002. var mesh = _a[_i];
  32003. mesh._markSubMeshesAsAttributesDirty();
  32004. }
  32005. };
  32006. Geometry.prototype.load = function (scene, onLoaded) {
  32007. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32008. return;
  32009. }
  32010. if (this.isReady()) {
  32011. if (onLoaded) {
  32012. onLoaded();
  32013. }
  32014. return;
  32015. }
  32016. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32017. this._queueLoad(scene, onLoaded);
  32018. };
  32019. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  32020. var _this = this;
  32021. if (!this.delayLoadingFile) {
  32022. return;
  32023. }
  32024. scene._addPendingData(this);
  32025. scene._loadFile(this.delayLoadingFile, function (data) {
  32026. if (!_this._delayLoadingFunction) {
  32027. return;
  32028. }
  32029. _this._delayLoadingFunction(JSON.parse(data), _this);
  32030. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32031. _this._delayInfo = [];
  32032. scene._removePendingData(_this);
  32033. var meshes = _this._meshes;
  32034. var numOfMeshes = meshes.length;
  32035. for (var index = 0; index < numOfMeshes; index++) {
  32036. _this._applyToMesh(meshes[index]);
  32037. }
  32038. if (onLoaded) {
  32039. onLoaded();
  32040. }
  32041. }, undefined, true);
  32042. };
  32043. /**
  32044. * Invert the geometry to move from a right handed system to a left handed one.
  32045. */
  32046. Geometry.prototype.toLeftHanded = function () {
  32047. // Flip faces
  32048. var tIndices = this.getIndices(false);
  32049. if (tIndices != null && tIndices.length > 0) {
  32050. for (var i = 0; i < tIndices.length; i += 3) {
  32051. var tTemp = tIndices[i + 0];
  32052. tIndices[i + 0] = tIndices[i + 2];
  32053. tIndices[i + 2] = tTemp;
  32054. }
  32055. this.setIndices(tIndices);
  32056. }
  32057. // Negate position.z
  32058. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  32059. if (tPositions != null && tPositions.length > 0) {
  32060. for (var i = 0; i < tPositions.length; i += 3) {
  32061. tPositions[i + 2] = -tPositions[i + 2];
  32062. }
  32063. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  32064. }
  32065. // Negate normal.z
  32066. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  32067. if (tNormals != null && tNormals.length > 0) {
  32068. for (var i = 0; i < tNormals.length; i += 3) {
  32069. tNormals[i + 2] = -tNormals[i + 2];
  32070. }
  32071. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  32072. }
  32073. };
  32074. // Cache
  32075. Geometry.prototype._resetPointsArrayCache = function () {
  32076. this._positions = null;
  32077. };
  32078. Geometry.prototype._generatePointsArray = function () {
  32079. if (this._positions)
  32080. return true;
  32081. this._positions = [];
  32082. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32083. if (!data) {
  32084. return false;
  32085. }
  32086. for (var index = 0; index < data.length; index += 3) {
  32087. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  32088. }
  32089. return true;
  32090. };
  32091. Geometry.prototype.isDisposed = function () {
  32092. return this._isDisposed;
  32093. };
  32094. Geometry.prototype._disposeVertexArrayObjects = function () {
  32095. if (this._vertexArrayObjects) {
  32096. for (var kind in this._vertexArrayObjects) {
  32097. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  32098. }
  32099. this._vertexArrayObjects = {};
  32100. }
  32101. };
  32102. Geometry.prototype.dispose = function () {
  32103. var meshes = this._meshes;
  32104. var numOfMeshes = meshes.length;
  32105. var index;
  32106. for (index = 0; index < numOfMeshes; index++) {
  32107. this.releaseForMesh(meshes[index]);
  32108. }
  32109. this._meshes = [];
  32110. this._disposeVertexArrayObjects();
  32111. for (var kind in this._vertexBuffers) {
  32112. this._vertexBuffers[kind].dispose();
  32113. }
  32114. this._vertexBuffers = {};
  32115. this._totalVertices = 0;
  32116. if (this._indexBuffer) {
  32117. this._engine._releaseBuffer(this._indexBuffer);
  32118. }
  32119. this._indexBuffer = null;
  32120. this._indices = [];
  32121. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32122. this.delayLoadingFile = null;
  32123. this._delayLoadingFunction = null;
  32124. this._delayInfo = [];
  32125. this._boundingInfo = null;
  32126. this._scene.removeGeometry(this);
  32127. this._isDisposed = true;
  32128. };
  32129. Geometry.prototype.copy = function (id) {
  32130. var vertexData = new BABYLON.VertexData();
  32131. vertexData.indices = [];
  32132. var indices = this.getIndices();
  32133. if (indices) {
  32134. for (var index = 0; index < indices.length; index++) {
  32135. vertexData.indices.push(indices[index]);
  32136. }
  32137. }
  32138. var updatable = false;
  32139. var stopChecking = false;
  32140. var kind;
  32141. for (kind in this._vertexBuffers) {
  32142. // using slice() to make a copy of the array and not just reference it
  32143. var data = this.getVerticesData(kind);
  32144. if (data instanceof Float32Array) {
  32145. vertexData.set(new Float32Array(data), kind);
  32146. }
  32147. else {
  32148. vertexData.set(data.slice(0), kind);
  32149. }
  32150. if (!stopChecking) {
  32151. var vb = this.getVertexBuffer(kind);
  32152. if (vb) {
  32153. updatable = vb.isUpdatable();
  32154. stopChecking = !updatable;
  32155. }
  32156. }
  32157. }
  32158. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  32159. geometry.delayLoadState = this.delayLoadState;
  32160. geometry.delayLoadingFile = this.delayLoadingFile;
  32161. geometry._delayLoadingFunction = this._delayLoadingFunction;
  32162. for (kind in this._delayInfo) {
  32163. geometry._delayInfo = geometry._delayInfo || [];
  32164. geometry._delayInfo.push(kind);
  32165. }
  32166. // Bounding info
  32167. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32168. return geometry;
  32169. };
  32170. Geometry.prototype.serialize = function () {
  32171. var serializationObject = {};
  32172. serializationObject.id = this.id;
  32173. serializationObject.updatable = this._updatable;
  32174. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32175. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32176. }
  32177. return serializationObject;
  32178. };
  32179. Geometry.prototype.toNumberArray = function (origin) {
  32180. if (Array.isArray(origin)) {
  32181. return origin;
  32182. }
  32183. else {
  32184. return Array.prototype.slice.call(origin);
  32185. }
  32186. };
  32187. Geometry.prototype.serializeVerticeData = function () {
  32188. var serializationObject = this.serialize();
  32189. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32190. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  32191. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  32192. serializationObject.positions._updatable = true;
  32193. }
  32194. }
  32195. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32196. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  32197. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  32198. serializationObject.normals._updatable = true;
  32199. }
  32200. }
  32201. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32202. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  32203. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  32204. serializationObject.uvs._updatable = true;
  32205. }
  32206. }
  32207. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32208. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  32209. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  32210. serializationObject.uv2s._updatable = true;
  32211. }
  32212. }
  32213. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32214. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  32215. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  32216. serializationObject.uv3s._updatable = true;
  32217. }
  32218. }
  32219. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32220. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  32221. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  32222. serializationObject.uv4s._updatable = true;
  32223. }
  32224. }
  32225. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32226. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  32227. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  32228. serializationObject.uv5s._updatable = true;
  32229. }
  32230. }
  32231. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32232. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  32233. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  32234. serializationObject.uv6s._updatable = true;
  32235. }
  32236. }
  32237. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32238. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  32239. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  32240. serializationObject.colors._updatable = true;
  32241. }
  32242. }
  32243. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32244. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  32245. serializationObject.matricesIndices._isExpanded = true;
  32246. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32247. serializationObject.matricesIndices._updatable = true;
  32248. }
  32249. }
  32250. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32251. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  32252. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32253. serializationObject.matricesWeights._updatable = true;
  32254. }
  32255. }
  32256. serializationObject.indices = this.toNumberArray(this.getIndices());
  32257. return serializationObject;
  32258. };
  32259. // Statics
  32260. Geometry.ExtractFromMesh = function (mesh, id) {
  32261. var geometry = mesh._geometry;
  32262. if (!geometry) {
  32263. return null;
  32264. }
  32265. return geometry.copy(id);
  32266. };
  32267. /**
  32268. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  32269. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  32270. * Be aware Math.random() could cause collisions, but:
  32271. * "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"
  32272. */
  32273. Geometry.RandomId = function () {
  32274. return BABYLON.Tools.RandomId();
  32275. };
  32276. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  32277. var scene = mesh.getScene();
  32278. // Geometry
  32279. var geometryId = parsedGeometry.geometryId;
  32280. if (geometryId) {
  32281. var geometry = scene.getGeometryByID(geometryId);
  32282. if (geometry) {
  32283. geometry.applyToMesh(mesh);
  32284. }
  32285. }
  32286. else if (parsedGeometry instanceof ArrayBuffer) {
  32287. var binaryInfo = mesh._binaryInfo;
  32288. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  32289. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  32290. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  32291. }
  32292. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  32293. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  32294. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  32295. }
  32296. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  32297. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  32298. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  32299. }
  32300. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  32301. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  32302. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  32303. }
  32304. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  32305. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  32306. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  32307. }
  32308. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  32309. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  32310. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  32311. }
  32312. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  32313. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  32314. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  32315. }
  32316. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  32317. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  32318. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  32319. }
  32320. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  32321. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  32322. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  32323. }
  32324. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  32325. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  32326. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  32327. }
  32328. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  32329. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  32330. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  32331. }
  32332. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  32333. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  32334. mesh.setIndices(indicesData, null);
  32335. }
  32336. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  32337. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  32338. mesh.subMeshes = [];
  32339. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  32340. var materialIndex = subMeshesData[(i * 5) + 0];
  32341. var verticesStart = subMeshesData[(i * 5) + 1];
  32342. var verticesCount = subMeshesData[(i * 5) + 2];
  32343. var indexStart = subMeshesData[(i * 5) + 3];
  32344. var indexCount = subMeshesData[(i * 5) + 4];
  32345. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  32346. }
  32347. }
  32348. }
  32349. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  32350. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  32351. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  32352. if (parsedGeometry.uvs) {
  32353. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  32354. }
  32355. if (parsedGeometry.uvs2) {
  32356. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  32357. }
  32358. if (parsedGeometry.uvs3) {
  32359. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  32360. }
  32361. if (parsedGeometry.uvs4) {
  32362. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  32363. }
  32364. if (parsedGeometry.uvs5) {
  32365. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  32366. }
  32367. if (parsedGeometry.uvs6) {
  32368. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  32369. }
  32370. if (parsedGeometry.colors) {
  32371. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  32372. }
  32373. if (parsedGeometry.matricesIndices) {
  32374. if (!parsedGeometry.matricesIndices._isExpanded) {
  32375. var floatIndices = [];
  32376. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32377. var matricesIndex = parsedGeometry.matricesIndices[i];
  32378. floatIndices.push(matricesIndex & 0x000000FF);
  32379. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32380. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32381. floatIndices.push(matricesIndex >> 24);
  32382. }
  32383. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  32384. }
  32385. else {
  32386. delete parsedGeometry.matricesIndices._isExpanded;
  32387. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  32388. }
  32389. }
  32390. if (parsedGeometry.matricesIndicesExtra) {
  32391. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32392. var floatIndices = [];
  32393. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32394. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32395. floatIndices.push(matricesIndex & 0x000000FF);
  32396. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32397. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32398. floatIndices.push(matricesIndex >> 24);
  32399. }
  32400. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  32401. }
  32402. else {
  32403. delete parsedGeometry.matricesIndices._isExpanded;
  32404. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  32405. }
  32406. }
  32407. if (parsedGeometry.matricesWeights) {
  32408. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  32409. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  32410. }
  32411. if (parsedGeometry.matricesWeightsExtra) {
  32412. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  32413. }
  32414. mesh.setIndices(parsedGeometry.indices, null);
  32415. }
  32416. // SubMeshes
  32417. if (parsedGeometry.subMeshes) {
  32418. mesh.subMeshes = [];
  32419. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32420. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32421. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32422. }
  32423. }
  32424. // Flat shading
  32425. if (mesh._shouldGenerateFlatShading) {
  32426. mesh.convertToFlatShadedMesh();
  32427. delete mesh._shouldGenerateFlatShading;
  32428. }
  32429. // Update
  32430. mesh.computeWorldMatrix(true);
  32431. // Octree
  32432. var sceneOctree = scene.selectionOctree;
  32433. if (sceneOctree !== undefined && sceneOctree !== null) {
  32434. sceneOctree.addMesh(mesh);
  32435. }
  32436. };
  32437. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  32438. var epsilon = 1e-3;
  32439. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  32440. return;
  32441. }
  32442. var noInfluenceBoneIndex = 0.0;
  32443. if (parsedGeometry.skeletonId > -1) {
  32444. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  32445. if (!skeleton) {
  32446. return;
  32447. }
  32448. noInfluenceBoneIndex = skeleton.bones.length;
  32449. }
  32450. else {
  32451. return;
  32452. }
  32453. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32454. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32455. var matricesWeights = parsedGeometry.matricesWeights;
  32456. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  32457. var influencers = parsedGeometry.numBoneInfluencer;
  32458. var size = matricesWeights.length;
  32459. for (var i = 0; i < size; i += 4) {
  32460. var weight = 0.0;
  32461. var firstZeroWeight = -1;
  32462. for (var j = 0; j < 4; j++) {
  32463. var w = matricesWeights[i + j];
  32464. weight += w;
  32465. if (w < epsilon && firstZeroWeight < 0) {
  32466. firstZeroWeight = j;
  32467. }
  32468. }
  32469. if (matricesWeightsExtra) {
  32470. for (var j = 0; j < 4; j++) {
  32471. var w = matricesWeightsExtra[i + j];
  32472. weight += w;
  32473. if (w < epsilon && firstZeroWeight < 0) {
  32474. firstZeroWeight = j + 4;
  32475. }
  32476. }
  32477. }
  32478. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32479. firstZeroWeight = influencers - 1;
  32480. }
  32481. if (weight > epsilon) {
  32482. var mweight = 1.0 / weight;
  32483. for (var j = 0; j < 4; j++) {
  32484. matricesWeights[i + j] *= mweight;
  32485. }
  32486. if (matricesWeightsExtra) {
  32487. for (var j = 0; j < 4; j++) {
  32488. matricesWeightsExtra[i + j] *= mweight;
  32489. }
  32490. }
  32491. }
  32492. else {
  32493. if (firstZeroWeight >= 4) {
  32494. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32495. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32496. }
  32497. else {
  32498. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32499. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32500. }
  32501. }
  32502. }
  32503. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32504. if (parsedGeometry.matricesWeightsExtra) {
  32505. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32506. }
  32507. };
  32508. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32509. if (scene.getGeometryByID(parsedVertexData.id)) {
  32510. return null; // null since geometry could be something else than a box...
  32511. }
  32512. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  32513. if (BABYLON.Tags) {
  32514. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32515. }
  32516. if (parsedVertexData.delayLoadingFile) {
  32517. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32518. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32519. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32520. geometry._delayInfo = [];
  32521. if (parsedVertexData.hasUVs) {
  32522. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32523. }
  32524. if (parsedVertexData.hasUVs2) {
  32525. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32526. }
  32527. if (parsedVertexData.hasUVs3) {
  32528. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32529. }
  32530. if (parsedVertexData.hasUVs4) {
  32531. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32532. }
  32533. if (parsedVertexData.hasUVs5) {
  32534. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32535. }
  32536. if (parsedVertexData.hasUVs6) {
  32537. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32538. }
  32539. if (parsedVertexData.hasColors) {
  32540. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32541. }
  32542. if (parsedVertexData.hasMatricesIndices) {
  32543. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32544. }
  32545. if (parsedVertexData.hasMatricesWeights) {
  32546. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32547. }
  32548. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32549. }
  32550. else {
  32551. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32552. }
  32553. scene.pushGeometry(geometry, true);
  32554. return geometry;
  32555. };
  32556. return Geometry;
  32557. }());
  32558. BABYLON.Geometry = Geometry;
  32559. /////// Primitives //////////////////////////////////////////////
  32560. //export module Geometry.Primitives {
  32561. /// Abstract class
  32562. var _PrimitiveGeometry = /** @class */ (function (_super) {
  32563. __extends(_PrimitiveGeometry, _super);
  32564. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  32565. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  32566. if (mesh === void 0) { mesh = null; }
  32567. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  32568. _this._canBeRegenerated = _canBeRegenerated;
  32569. _this._beingRegenerated = true;
  32570. _this.regenerate();
  32571. _this._beingRegenerated = false;
  32572. return _this;
  32573. }
  32574. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  32575. return this._canBeRegenerated;
  32576. };
  32577. _PrimitiveGeometry.prototype.regenerate = function () {
  32578. if (!this._canBeRegenerated) {
  32579. return;
  32580. }
  32581. this._beingRegenerated = true;
  32582. this.setAllVerticesData(this._regenerateVertexData(), false);
  32583. this._beingRegenerated = false;
  32584. };
  32585. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  32586. return _super.prototype.copy.call(this, id);
  32587. };
  32588. // overrides
  32589. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32590. if (!this._beingRegenerated) {
  32591. return;
  32592. }
  32593. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32594. };
  32595. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  32596. if (!this._beingRegenerated) {
  32597. return;
  32598. }
  32599. _super.prototype.setVerticesData.call(this, kind, data, false);
  32600. };
  32601. // to override
  32602. // protected
  32603. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  32604. throw new Error("Abstract method");
  32605. };
  32606. _PrimitiveGeometry.prototype.copy = function (id) {
  32607. throw new Error("Must be overriden in sub-classes.");
  32608. };
  32609. _PrimitiveGeometry.prototype.serialize = function () {
  32610. var serializationObject = _super.prototype.serialize.call(this);
  32611. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32612. return serializationObject;
  32613. };
  32614. return _PrimitiveGeometry;
  32615. }(Geometry));
  32616. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  32617. var RibbonGeometry = /** @class */ (function (_super) {
  32618. __extends(RibbonGeometry, _super);
  32619. // Members
  32620. function RibbonGeometry(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32621. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32622. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32623. _this.pathArray = pathArray;
  32624. _this.closeArray = closeArray;
  32625. _this.closePath = closePath;
  32626. _this.offset = offset;
  32627. _this.side = side;
  32628. return _this;
  32629. }
  32630. RibbonGeometry.prototype._regenerateVertexData = function () {
  32631. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32632. };
  32633. RibbonGeometry.prototype.copy = function (id) {
  32634. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  32635. };
  32636. return RibbonGeometry;
  32637. }(_PrimitiveGeometry));
  32638. BABYLON.RibbonGeometry = RibbonGeometry;
  32639. var BoxGeometry = /** @class */ (function (_super) {
  32640. __extends(BoxGeometry, _super);
  32641. // Members
  32642. function BoxGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32643. if (mesh === void 0) { mesh = null; }
  32644. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32645. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32646. _this.size = size;
  32647. _this.side = side;
  32648. return _this;
  32649. }
  32650. BoxGeometry.prototype._regenerateVertexData = function () {
  32651. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32652. };
  32653. BoxGeometry.prototype.copy = function (id) {
  32654. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  32655. };
  32656. BoxGeometry.prototype.serialize = function () {
  32657. var serializationObject = _super.prototype.serialize.call(this);
  32658. serializationObject.size = this.size;
  32659. return serializationObject;
  32660. };
  32661. BoxGeometry.Parse = function (parsedBox, scene) {
  32662. if (scene.getGeometryByID(parsedBox.id)) {
  32663. return null; // null since geometry could be something else than a box...
  32664. }
  32665. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32666. if (BABYLON.Tags) {
  32667. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32668. }
  32669. scene.pushGeometry(box, true);
  32670. return box;
  32671. };
  32672. return BoxGeometry;
  32673. }(_PrimitiveGeometry));
  32674. BABYLON.BoxGeometry = BoxGeometry;
  32675. var SphereGeometry = /** @class */ (function (_super) {
  32676. __extends(SphereGeometry, _super);
  32677. function SphereGeometry(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32678. if (mesh === void 0) { mesh = null; }
  32679. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32680. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32681. _this.segments = segments;
  32682. _this.diameter = diameter;
  32683. _this.side = side;
  32684. return _this;
  32685. }
  32686. SphereGeometry.prototype._regenerateVertexData = function () {
  32687. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32688. };
  32689. SphereGeometry.prototype.copy = function (id) {
  32690. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32691. };
  32692. SphereGeometry.prototype.serialize = function () {
  32693. var serializationObject = _super.prototype.serialize.call(this);
  32694. serializationObject.segments = this.segments;
  32695. serializationObject.diameter = this.diameter;
  32696. return serializationObject;
  32697. };
  32698. SphereGeometry.Parse = function (parsedSphere, scene) {
  32699. if (scene.getGeometryByID(parsedSphere.id)) {
  32700. return null; // null since geometry could be something else than a sphere...
  32701. }
  32702. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32703. if (BABYLON.Tags) {
  32704. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32705. }
  32706. scene.pushGeometry(sphere, true);
  32707. return sphere;
  32708. };
  32709. return SphereGeometry;
  32710. }(_PrimitiveGeometry));
  32711. BABYLON.SphereGeometry = SphereGeometry;
  32712. var DiscGeometry = /** @class */ (function (_super) {
  32713. __extends(DiscGeometry, _super);
  32714. // Members
  32715. function DiscGeometry(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32716. if (mesh === void 0) { mesh = null; }
  32717. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32718. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32719. _this.radius = radius;
  32720. _this.tessellation = tessellation;
  32721. _this.side = side;
  32722. return _this;
  32723. }
  32724. DiscGeometry.prototype._regenerateVertexData = function () {
  32725. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32726. };
  32727. DiscGeometry.prototype.copy = function (id) {
  32728. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32729. };
  32730. return DiscGeometry;
  32731. }(_PrimitiveGeometry));
  32732. BABYLON.DiscGeometry = DiscGeometry;
  32733. var CylinderGeometry = /** @class */ (function (_super) {
  32734. __extends(CylinderGeometry, _super);
  32735. function CylinderGeometry(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32736. if (subdivisions === void 0) { subdivisions = 1; }
  32737. if (mesh === void 0) { mesh = null; }
  32738. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32739. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32740. _this.height = height;
  32741. _this.diameterTop = diameterTop;
  32742. _this.diameterBottom = diameterBottom;
  32743. _this.tessellation = tessellation;
  32744. _this.subdivisions = subdivisions;
  32745. _this.side = side;
  32746. return _this;
  32747. }
  32748. CylinderGeometry.prototype._regenerateVertexData = function () {
  32749. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32750. };
  32751. CylinderGeometry.prototype.copy = function (id) {
  32752. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32753. };
  32754. CylinderGeometry.prototype.serialize = function () {
  32755. var serializationObject = _super.prototype.serialize.call(this);
  32756. serializationObject.height = this.height;
  32757. serializationObject.diameterTop = this.diameterTop;
  32758. serializationObject.diameterBottom = this.diameterBottom;
  32759. serializationObject.tessellation = this.tessellation;
  32760. return serializationObject;
  32761. };
  32762. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  32763. if (scene.getGeometryByID(parsedCylinder.id)) {
  32764. return null; // null since geometry could be something else than a cylinder...
  32765. }
  32766. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32767. if (BABYLON.Tags) {
  32768. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32769. }
  32770. scene.pushGeometry(cylinder, true);
  32771. return cylinder;
  32772. };
  32773. return CylinderGeometry;
  32774. }(_PrimitiveGeometry));
  32775. BABYLON.CylinderGeometry = CylinderGeometry;
  32776. var TorusGeometry = /** @class */ (function (_super) {
  32777. __extends(TorusGeometry, _super);
  32778. function TorusGeometry(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32779. if (mesh === void 0) { mesh = null; }
  32780. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32781. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32782. _this.diameter = diameter;
  32783. _this.thickness = thickness;
  32784. _this.tessellation = tessellation;
  32785. _this.side = side;
  32786. return _this;
  32787. }
  32788. TorusGeometry.prototype._regenerateVertexData = function () {
  32789. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32790. };
  32791. TorusGeometry.prototype.copy = function (id) {
  32792. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32793. };
  32794. TorusGeometry.prototype.serialize = function () {
  32795. var serializationObject = _super.prototype.serialize.call(this);
  32796. serializationObject.diameter = this.diameter;
  32797. serializationObject.thickness = this.thickness;
  32798. serializationObject.tessellation = this.tessellation;
  32799. return serializationObject;
  32800. };
  32801. TorusGeometry.Parse = function (parsedTorus, scene) {
  32802. if (scene.getGeometryByID(parsedTorus.id)) {
  32803. return null; // null since geometry could be something else than a torus...
  32804. }
  32805. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32806. if (BABYLON.Tags) {
  32807. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32808. }
  32809. scene.pushGeometry(torus, true);
  32810. return torus;
  32811. };
  32812. return TorusGeometry;
  32813. }(_PrimitiveGeometry));
  32814. BABYLON.TorusGeometry = TorusGeometry;
  32815. var GroundGeometry = /** @class */ (function (_super) {
  32816. __extends(GroundGeometry, _super);
  32817. function GroundGeometry(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32818. if (mesh === void 0) { mesh = null; }
  32819. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32820. _this.width = width;
  32821. _this.height = height;
  32822. _this.subdivisions = subdivisions;
  32823. return _this;
  32824. }
  32825. GroundGeometry.prototype._regenerateVertexData = function () {
  32826. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32827. };
  32828. GroundGeometry.prototype.copy = function (id) {
  32829. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32830. };
  32831. GroundGeometry.prototype.serialize = function () {
  32832. var serializationObject = _super.prototype.serialize.call(this);
  32833. serializationObject.width = this.width;
  32834. serializationObject.height = this.height;
  32835. serializationObject.subdivisions = this.subdivisions;
  32836. return serializationObject;
  32837. };
  32838. GroundGeometry.Parse = function (parsedGround, scene) {
  32839. if (scene.getGeometryByID(parsedGround.id)) {
  32840. return null; // null since geometry could be something else than a ground...
  32841. }
  32842. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32843. if (BABYLON.Tags) {
  32844. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32845. }
  32846. scene.pushGeometry(ground, true);
  32847. return ground;
  32848. };
  32849. return GroundGeometry;
  32850. }(_PrimitiveGeometry));
  32851. BABYLON.GroundGeometry = GroundGeometry;
  32852. var TiledGroundGeometry = /** @class */ (function (_super) {
  32853. __extends(TiledGroundGeometry, _super);
  32854. function TiledGroundGeometry(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32855. if (mesh === void 0) { mesh = null; }
  32856. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32857. _this.xmin = xmin;
  32858. _this.zmin = zmin;
  32859. _this.xmax = xmax;
  32860. _this.zmax = zmax;
  32861. _this.subdivisions = subdivisions;
  32862. _this.precision = precision;
  32863. return _this;
  32864. }
  32865. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  32866. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32867. };
  32868. TiledGroundGeometry.prototype.copy = function (id) {
  32869. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32870. };
  32871. return TiledGroundGeometry;
  32872. }(_PrimitiveGeometry));
  32873. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  32874. var PlaneGeometry = /** @class */ (function (_super) {
  32875. __extends(PlaneGeometry, _super);
  32876. function PlaneGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32877. if (mesh === void 0) { mesh = null; }
  32878. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32879. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32880. _this.size = size;
  32881. _this.side = side;
  32882. return _this;
  32883. }
  32884. PlaneGeometry.prototype._regenerateVertexData = function () {
  32885. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32886. };
  32887. PlaneGeometry.prototype.copy = function (id) {
  32888. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32889. };
  32890. PlaneGeometry.prototype.serialize = function () {
  32891. var serializationObject = _super.prototype.serialize.call(this);
  32892. serializationObject.size = this.size;
  32893. return serializationObject;
  32894. };
  32895. PlaneGeometry.Parse = function (parsedPlane, scene) {
  32896. if (scene.getGeometryByID(parsedPlane.id)) {
  32897. return null; // null since geometry could be something else than a ground...
  32898. }
  32899. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32900. if (BABYLON.Tags) {
  32901. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32902. }
  32903. scene.pushGeometry(plane, true);
  32904. return plane;
  32905. };
  32906. return PlaneGeometry;
  32907. }(_PrimitiveGeometry));
  32908. BABYLON.PlaneGeometry = PlaneGeometry;
  32909. var TorusKnotGeometry = /** @class */ (function (_super) {
  32910. __extends(TorusKnotGeometry, _super);
  32911. function TorusKnotGeometry(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32912. if (mesh === void 0) { mesh = null; }
  32913. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32914. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32915. _this.radius = radius;
  32916. _this.tube = tube;
  32917. _this.radialSegments = radialSegments;
  32918. _this.tubularSegments = tubularSegments;
  32919. _this.p = p;
  32920. _this.q = q;
  32921. _this.side = side;
  32922. return _this;
  32923. }
  32924. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  32925. 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 });
  32926. };
  32927. TorusKnotGeometry.prototype.copy = function (id) {
  32928. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32929. };
  32930. TorusKnotGeometry.prototype.serialize = function () {
  32931. var serializationObject = _super.prototype.serialize.call(this);
  32932. serializationObject.radius = this.radius;
  32933. serializationObject.tube = this.tube;
  32934. serializationObject.radialSegments = this.radialSegments;
  32935. serializationObject.tubularSegments = this.tubularSegments;
  32936. serializationObject.p = this.p;
  32937. serializationObject.q = this.q;
  32938. return serializationObject;
  32939. };
  32940. ;
  32941. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  32942. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32943. return null; // null since geometry could be something else than a ground...
  32944. }
  32945. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32946. if (BABYLON.Tags) {
  32947. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32948. }
  32949. scene.pushGeometry(torusKnot, true);
  32950. return torusKnot;
  32951. };
  32952. return TorusKnotGeometry;
  32953. }(_PrimitiveGeometry));
  32954. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  32955. //}
  32956. })(BABYLON || (BABYLON = {}));
  32957. //# sourceMappingURL=babylon.geometry.js.map
  32958. var BABYLON;
  32959. (function (BABYLON) {
  32960. var PostProcessManager = /** @class */ (function () {
  32961. function PostProcessManager(scene) {
  32962. this._vertexBuffers = {};
  32963. this._scene = scene;
  32964. }
  32965. PostProcessManager.prototype._prepareBuffers = function () {
  32966. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32967. return;
  32968. }
  32969. // VBO
  32970. var vertices = [];
  32971. vertices.push(1, 1);
  32972. vertices.push(-1, 1);
  32973. vertices.push(-1, -1);
  32974. vertices.push(1, -1);
  32975. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32976. this._buildIndexBuffer();
  32977. };
  32978. PostProcessManager.prototype._buildIndexBuffer = function () {
  32979. // Indices
  32980. var indices = [];
  32981. indices.push(0);
  32982. indices.push(1);
  32983. indices.push(2);
  32984. indices.push(0);
  32985. indices.push(2);
  32986. indices.push(3);
  32987. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32988. };
  32989. PostProcessManager.prototype._rebuild = function () {
  32990. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32991. if (!vb) {
  32992. return;
  32993. }
  32994. vb._rebuild();
  32995. this._buildIndexBuffer();
  32996. };
  32997. // Methods
  32998. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32999. if (sourceTexture === void 0) { sourceTexture = null; }
  33000. if (postProcesses === void 0) { postProcesses = null; }
  33001. var camera = this._scene.activeCamera;
  33002. if (!camera) {
  33003. return false;
  33004. }
  33005. var postProcesses = postProcesses || camera._postProcesses;
  33006. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  33007. return false;
  33008. }
  33009. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  33010. return true;
  33011. };
  33012. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  33013. if (targetTexture === void 0) { targetTexture = null; }
  33014. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  33015. var engine = this._scene.getEngine();
  33016. for (var index = 0; index < postProcesses.length; index++) {
  33017. if (index < postProcesses.length - 1) {
  33018. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  33019. }
  33020. else {
  33021. if (targetTexture) {
  33022. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  33023. }
  33024. else {
  33025. engine.restoreDefaultFramebuffer();
  33026. }
  33027. }
  33028. var pp = postProcesses[index];
  33029. var effect = pp.apply();
  33030. if (effect) {
  33031. pp.onBeforeRenderObservable.notifyObservers(effect);
  33032. // VBOs
  33033. this._prepareBuffers();
  33034. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33035. // Draw order
  33036. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  33037. pp.onAfterRenderObservable.notifyObservers(effect);
  33038. }
  33039. }
  33040. // Restore depth buffer
  33041. engine.setDepthBuffer(true);
  33042. engine.setDepthWrite(true);
  33043. };
  33044. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  33045. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  33046. var camera = this._scene.activeCamera;
  33047. if (!camera) {
  33048. return;
  33049. }
  33050. postProcesses = postProcesses || camera._postProcesses;
  33051. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  33052. return;
  33053. }
  33054. var engine = this._scene.getEngine();
  33055. for (var index = 0, len = postProcesses.length; index < len; index++) {
  33056. if (index < len - 1) {
  33057. postProcesses[index + 1].activate(camera, targetTexture);
  33058. }
  33059. else {
  33060. if (targetTexture) {
  33061. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  33062. }
  33063. else {
  33064. engine.restoreDefaultFramebuffer();
  33065. }
  33066. }
  33067. if (doNotPresent) {
  33068. break;
  33069. }
  33070. var pp = postProcesses[index];
  33071. var effect = pp.apply();
  33072. if (effect) {
  33073. pp.onBeforeRenderObservable.notifyObservers(effect);
  33074. // VBOs
  33075. this._prepareBuffers();
  33076. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33077. // Draw order
  33078. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  33079. pp.onAfterRenderObservable.notifyObservers(effect);
  33080. }
  33081. }
  33082. // Restore states
  33083. engine.setDepthBuffer(true);
  33084. engine.setDepthWrite(true);
  33085. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33086. };
  33087. PostProcessManager.prototype.dispose = function () {
  33088. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33089. if (buffer) {
  33090. buffer.dispose();
  33091. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  33092. }
  33093. if (this._indexBuffer) {
  33094. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33095. this._indexBuffer = null;
  33096. }
  33097. };
  33098. return PostProcessManager;
  33099. }());
  33100. BABYLON.PostProcessManager = PostProcessManager;
  33101. })(BABYLON || (BABYLON = {}));
  33102. //# sourceMappingURL=babylon.postProcessManager.js.map
  33103. var BABYLON;
  33104. (function (BABYLON) {
  33105. /**
  33106. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  33107. */
  33108. var PerformanceMonitor = /** @class */ (function () {
  33109. /**
  33110. * constructor
  33111. * @param frameSampleSize The number of samples required to saturate the sliding window
  33112. */
  33113. function PerformanceMonitor(frameSampleSize) {
  33114. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  33115. this._enabled = true;
  33116. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  33117. }
  33118. /**
  33119. * Samples current frame
  33120. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  33121. */
  33122. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  33123. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  33124. if (!this._enabled)
  33125. return;
  33126. if (this._lastFrameTimeMs != null) {
  33127. var dt = timeMs - this._lastFrameTimeMs;
  33128. this._rollingFrameTime.add(dt);
  33129. }
  33130. this._lastFrameTimeMs = timeMs;
  33131. };
  33132. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  33133. /**
  33134. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  33135. * @return Average frame time in milliseconds
  33136. */
  33137. get: function () {
  33138. return this._rollingFrameTime.average;
  33139. },
  33140. enumerable: true,
  33141. configurable: true
  33142. });
  33143. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  33144. /**
  33145. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  33146. * @return Frame time variance in milliseconds squared
  33147. */
  33148. get: function () {
  33149. return this._rollingFrameTime.variance;
  33150. },
  33151. enumerable: true,
  33152. configurable: true
  33153. });
  33154. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  33155. /**
  33156. * Returns the frame time of the most recent frame
  33157. * @return Frame time in milliseconds
  33158. */
  33159. get: function () {
  33160. return this._rollingFrameTime.history(0);
  33161. },
  33162. enumerable: true,
  33163. configurable: true
  33164. });
  33165. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  33166. /**
  33167. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  33168. * @return Framerate in frames per second
  33169. */
  33170. get: function () {
  33171. return 1000.0 / this._rollingFrameTime.average;
  33172. },
  33173. enumerable: true,
  33174. configurable: true
  33175. });
  33176. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  33177. /**
  33178. * Returns the average framerate in frames per second using the most recent frame time
  33179. * @return Framerate in frames per second
  33180. */
  33181. get: function () {
  33182. var history = this._rollingFrameTime.history(0);
  33183. if (history === 0) {
  33184. return 0;
  33185. }
  33186. return 1000.0 / history;
  33187. },
  33188. enumerable: true,
  33189. configurable: true
  33190. });
  33191. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  33192. /**
  33193. * Returns true if enough samples have been taken to completely fill the sliding window
  33194. * @return true if saturated
  33195. */
  33196. get: function () {
  33197. return this._rollingFrameTime.isSaturated();
  33198. },
  33199. enumerable: true,
  33200. configurable: true
  33201. });
  33202. /**
  33203. * Enables contributions to the sliding window sample set
  33204. */
  33205. PerformanceMonitor.prototype.enable = function () {
  33206. this._enabled = true;
  33207. };
  33208. /**
  33209. * Disables contributions to the sliding window sample set
  33210. * Samples will not be interpolated over the disabled period
  33211. */
  33212. PerformanceMonitor.prototype.disable = function () {
  33213. this._enabled = false;
  33214. //clear last sample to avoid interpolating over the disabled period when next enabled
  33215. this._lastFrameTimeMs = null;
  33216. };
  33217. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  33218. /**
  33219. * Returns true if sampling is enabled
  33220. * @return true if enabled
  33221. */
  33222. get: function () {
  33223. return this._enabled;
  33224. },
  33225. enumerable: true,
  33226. configurable: true
  33227. });
  33228. /**
  33229. * Resets performance monitor
  33230. */
  33231. PerformanceMonitor.prototype.reset = function () {
  33232. //clear last sample to avoid interpolating over the disabled period when next enabled
  33233. this._lastFrameTimeMs = null;
  33234. //wipe record
  33235. this._rollingFrameTime.reset();
  33236. };
  33237. return PerformanceMonitor;
  33238. }());
  33239. BABYLON.PerformanceMonitor = PerformanceMonitor;
  33240. /**
  33241. * RollingAverage
  33242. *
  33243. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  33244. */
  33245. var RollingAverage = /** @class */ (function () {
  33246. /**
  33247. * constructor
  33248. * @param length The number of samples required to saturate the sliding window
  33249. */
  33250. function RollingAverage(length) {
  33251. this._samples = new Array(length);
  33252. this.reset();
  33253. }
  33254. /**
  33255. * Adds a sample to the sample set
  33256. * @param v The sample value
  33257. */
  33258. RollingAverage.prototype.add = function (v) {
  33259. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  33260. var delta;
  33261. //we need to check if we've already wrapped round
  33262. if (this.isSaturated()) {
  33263. //remove bottom of stack from mean
  33264. var bottomValue = this._samples[this._pos];
  33265. delta = bottomValue - this.average;
  33266. this.average -= delta / (this._sampleCount - 1);
  33267. this._m2 -= delta * (bottomValue - this.average);
  33268. }
  33269. else {
  33270. this._sampleCount++;
  33271. }
  33272. //add new value to mean
  33273. delta = v - this.average;
  33274. this.average += delta / (this._sampleCount);
  33275. this._m2 += delta * (v - this.average);
  33276. //set the new variance
  33277. this.variance = this._m2 / (this._sampleCount - 1);
  33278. this._samples[this._pos] = v;
  33279. this._pos++;
  33280. this._pos %= this._samples.length; //positive wrap around
  33281. };
  33282. /**
  33283. * Returns previously added values or null if outside of history or outside the sliding window domain
  33284. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  33285. * @return Value previously recorded with add() or null if outside of range
  33286. */
  33287. RollingAverage.prototype.history = function (i) {
  33288. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  33289. return 0;
  33290. }
  33291. var i0 = this._wrapPosition(this._pos - 1.0);
  33292. return this._samples[this._wrapPosition(i0 - i)];
  33293. };
  33294. /**
  33295. * Returns true if enough samples have been taken to completely fill the sliding window
  33296. * @return true if sample-set saturated
  33297. */
  33298. RollingAverage.prototype.isSaturated = function () {
  33299. return this._sampleCount >= this._samples.length;
  33300. };
  33301. /**
  33302. * Resets the rolling average (equivalent to 0 samples taken so far)
  33303. */
  33304. RollingAverage.prototype.reset = function () {
  33305. this.average = 0;
  33306. this.variance = 0;
  33307. this._sampleCount = 0;
  33308. this._pos = 0;
  33309. this._m2 = 0;
  33310. };
  33311. /**
  33312. * Wraps a value around the sample range boundaries
  33313. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  33314. * @return Wrapped position in sample range
  33315. */
  33316. RollingAverage.prototype._wrapPosition = function (i) {
  33317. var max = this._samples.length;
  33318. return ((i % max) + max) % max;
  33319. };
  33320. return RollingAverage;
  33321. }());
  33322. BABYLON.RollingAverage = RollingAverage;
  33323. })(BABYLON || (BABYLON = {}));
  33324. //# sourceMappingURL=babylon.performanceMonitor.js.map
  33325. var BABYLON;
  33326. (function (BABYLON) {
  33327. /**
  33328. * This groups together the common properties used for image processing either in direct forward pass
  33329. * or through post processing effect depending on the use of the image processing pipeline in your scene
  33330. * or not.
  33331. */
  33332. var ImageProcessingConfiguration = /** @class */ (function () {
  33333. function ImageProcessingConfiguration() {
  33334. /**
  33335. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  33336. */
  33337. this.colorCurves = new BABYLON.ColorCurves();
  33338. this._colorCurvesEnabled = false;
  33339. this._colorGradingEnabled = false;
  33340. this._colorGradingWithGreenDepth = true;
  33341. this._colorGradingBGR = true;
  33342. this._exposure = 1.0;
  33343. this._toneMappingEnabled = false;
  33344. this._contrast = 1.0;
  33345. /**
  33346. * Vignette stretch size.
  33347. */
  33348. this.vignetteStretch = 0;
  33349. /**
  33350. * Vignette centre X Offset.
  33351. */
  33352. this.vignetteCentreX = 0;
  33353. /**
  33354. * Vignette centre Y Offset.
  33355. */
  33356. this.vignetteCentreY = 0;
  33357. /**
  33358. * Vignette weight or intensity of the vignette effect.
  33359. */
  33360. this.vignetteWeight = 1.5;
  33361. /**
  33362. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  33363. * if vignetteEnabled is set to true.
  33364. */
  33365. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  33366. /**
  33367. * Camera field of view used by the Vignette effect.
  33368. */
  33369. this.vignetteCameraFov = 0.5;
  33370. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  33371. this._vignetteEnabled = false;
  33372. this._applyByPostProcess = false;
  33373. this._isEnabled = true;
  33374. /**
  33375. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  33376. * @type {BABYLON.Observable}
  33377. */
  33378. this.onUpdateParameters = new BABYLON.Observable();
  33379. }
  33380. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  33381. /**
  33382. * Gets wether the color curves effect is enabled.
  33383. */
  33384. get: function () {
  33385. return this._colorCurvesEnabled;
  33386. },
  33387. /**
  33388. * Sets wether the color curves effect is enabled.
  33389. */
  33390. set: function (value) {
  33391. if (this._colorCurvesEnabled === value) {
  33392. return;
  33393. }
  33394. this._colorCurvesEnabled = value;
  33395. this._updateParameters();
  33396. },
  33397. enumerable: true,
  33398. configurable: true
  33399. });
  33400. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  33401. /**
  33402. * Gets wether the color grading effect is enabled.
  33403. */
  33404. get: function () {
  33405. return this._colorGradingEnabled;
  33406. },
  33407. /**
  33408. * Sets wether the color grading effect is enabled.
  33409. */
  33410. set: function (value) {
  33411. if (this._colorGradingEnabled === value) {
  33412. return;
  33413. }
  33414. this._colorGradingEnabled = value;
  33415. this._updateParameters();
  33416. },
  33417. enumerable: true,
  33418. configurable: true
  33419. });
  33420. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  33421. /**
  33422. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  33423. */
  33424. get: function () {
  33425. return this._colorGradingWithGreenDepth;
  33426. },
  33427. /**
  33428. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  33429. */
  33430. set: function (value) {
  33431. if (this._colorGradingWithGreenDepth === value) {
  33432. return;
  33433. }
  33434. this._colorGradingWithGreenDepth = value;
  33435. this._updateParameters();
  33436. },
  33437. enumerable: true,
  33438. configurable: true
  33439. });
  33440. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  33441. /**
  33442. * Gets wether the color grading texture contains BGR values.
  33443. */
  33444. get: function () {
  33445. return this._colorGradingBGR;
  33446. },
  33447. /**
  33448. * Sets wether the color grading texture contains BGR values.
  33449. */
  33450. set: function (value) {
  33451. if (this._colorGradingBGR === value) {
  33452. return;
  33453. }
  33454. this._colorGradingBGR = value;
  33455. this._updateParameters();
  33456. },
  33457. enumerable: true,
  33458. configurable: true
  33459. });
  33460. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  33461. /**
  33462. * Gets the Exposure used in the effect.
  33463. */
  33464. get: function () {
  33465. return this._exposure;
  33466. },
  33467. /**
  33468. * Sets the Exposure used in the effect.
  33469. */
  33470. set: function (value) {
  33471. if (this._exposure === value) {
  33472. return;
  33473. }
  33474. this._exposure = value;
  33475. this._updateParameters();
  33476. },
  33477. enumerable: true,
  33478. configurable: true
  33479. });
  33480. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  33481. /**
  33482. * Gets wether the tone mapping effect is enabled.
  33483. */
  33484. get: function () {
  33485. return this._toneMappingEnabled;
  33486. },
  33487. /**
  33488. * Sets wether the tone mapping effect is enabled.
  33489. */
  33490. set: function (value) {
  33491. if (this._toneMappingEnabled === value) {
  33492. return;
  33493. }
  33494. this._toneMappingEnabled = value;
  33495. this._updateParameters();
  33496. },
  33497. enumerable: true,
  33498. configurable: true
  33499. });
  33500. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  33501. /**
  33502. * Gets the contrast used in the effect.
  33503. */
  33504. get: function () {
  33505. return this._contrast;
  33506. },
  33507. /**
  33508. * Sets the contrast used in the effect.
  33509. */
  33510. set: function (value) {
  33511. if (this._contrast === value) {
  33512. return;
  33513. }
  33514. this._contrast = value;
  33515. this._updateParameters();
  33516. },
  33517. enumerable: true,
  33518. configurable: true
  33519. });
  33520. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  33521. /**
  33522. * Gets the vignette blend mode allowing different kind of effect.
  33523. */
  33524. get: function () {
  33525. return this._vignetteBlendMode;
  33526. },
  33527. /**
  33528. * Sets the vignette blend mode allowing different kind of effect.
  33529. */
  33530. set: function (value) {
  33531. if (this._vignetteBlendMode === value) {
  33532. return;
  33533. }
  33534. this._vignetteBlendMode = value;
  33535. this._updateParameters();
  33536. },
  33537. enumerable: true,
  33538. configurable: true
  33539. });
  33540. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  33541. /**
  33542. * Gets wether the vignette effect is enabled.
  33543. */
  33544. get: function () {
  33545. return this._vignetteEnabled;
  33546. },
  33547. /**
  33548. * Sets wether the vignette effect is enabled.
  33549. */
  33550. set: function (value) {
  33551. if (this._vignetteEnabled === value) {
  33552. return;
  33553. }
  33554. this._vignetteEnabled = value;
  33555. this._updateParameters();
  33556. },
  33557. enumerable: true,
  33558. configurable: true
  33559. });
  33560. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  33561. /**
  33562. * Gets wether the image processing is applied through a post process or not.
  33563. */
  33564. get: function () {
  33565. return this._applyByPostProcess;
  33566. },
  33567. /**
  33568. * Sets wether the image processing is applied through a post process or not.
  33569. */
  33570. set: function (value) {
  33571. if (this._applyByPostProcess === value) {
  33572. return;
  33573. }
  33574. this._applyByPostProcess = value;
  33575. this._updateParameters();
  33576. },
  33577. enumerable: true,
  33578. configurable: true
  33579. });
  33580. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  33581. /**
  33582. * Gets wether the image processing is enabled or not.
  33583. */
  33584. get: function () {
  33585. return this._isEnabled;
  33586. },
  33587. /**
  33588. * Sets wether the image processing is enabled or not.
  33589. */
  33590. set: function (value) {
  33591. if (this._isEnabled === value) {
  33592. return;
  33593. }
  33594. this._isEnabled = value;
  33595. this._updateParameters();
  33596. },
  33597. enumerable: true,
  33598. configurable: true
  33599. });
  33600. /**
  33601. * Method called each time the image processing information changes requires to recompile the effect.
  33602. */
  33603. ImageProcessingConfiguration.prototype._updateParameters = function () {
  33604. this.onUpdateParameters.notifyObservers(this);
  33605. };
  33606. ImageProcessingConfiguration.prototype.getClassName = function () {
  33607. return "ImageProcessingConfiguration";
  33608. };
  33609. /**
  33610. * Prepare the list of uniforms associated with the Image Processing effects.
  33611. * @param uniformsList The list of uniforms used in the effect
  33612. * @param defines the list of defines currently in use
  33613. */
  33614. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  33615. if (defines.EXPOSURE) {
  33616. uniforms.push("exposureLinear");
  33617. }
  33618. if (defines.CONTRAST) {
  33619. uniforms.push("contrast");
  33620. }
  33621. if (defines.COLORGRADING) {
  33622. uniforms.push("colorTransformSettings");
  33623. }
  33624. if (defines.VIGNETTE) {
  33625. uniforms.push("vInverseScreenSize");
  33626. uniforms.push("vignetteSettings1");
  33627. uniforms.push("vignetteSettings2");
  33628. }
  33629. if (defines.COLORCURVES) {
  33630. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  33631. }
  33632. };
  33633. /**
  33634. * Prepare the list of samplers associated with the Image Processing effects.
  33635. * @param uniformsList The list of uniforms used in the effect
  33636. * @param defines the list of defines currently in use
  33637. */
  33638. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  33639. if (defines.COLORGRADING) {
  33640. samplersList.push("txColorTransform");
  33641. }
  33642. };
  33643. /**
  33644. * Prepare the list of defines associated to the shader.
  33645. * @param defines the list of defines to complete
  33646. */
  33647. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  33648. if (forPostProcess === void 0) { forPostProcess = false; }
  33649. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  33650. defines.VIGNETTE = false;
  33651. defines.TONEMAPPING = false;
  33652. defines.CONTRAST = false;
  33653. defines.EXPOSURE = false;
  33654. defines.COLORCURVES = false;
  33655. defines.COLORGRADING = false;
  33656. defines.COLORGRADING3D = false;
  33657. defines.IMAGEPROCESSING = false;
  33658. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  33659. return;
  33660. }
  33661. defines.VIGNETTE = this.vignetteEnabled;
  33662. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  33663. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  33664. defines.TONEMAPPING = this.toneMappingEnabled;
  33665. defines.CONTRAST = (this.contrast !== 1.0);
  33666. defines.EXPOSURE = (this.exposure !== 1.0);
  33667. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  33668. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  33669. if (defines.COLORGRADING) {
  33670. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  33671. }
  33672. else {
  33673. defines.COLORGRADING3D = false;
  33674. }
  33675. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  33676. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  33677. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  33678. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  33679. };
  33680. /**
  33681. * Returns true if all the image processing information are ready.
  33682. */
  33683. ImageProcessingConfiguration.prototype.isReady = function () {
  33684. // Color Grading texure can not be none blocking.
  33685. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  33686. };
  33687. /**
  33688. * Binds the image processing to the shader.
  33689. * @param effect The effect to bind to
  33690. */
  33691. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  33692. if (aspectRatio === void 0) { aspectRatio = 1; }
  33693. // Color Curves
  33694. if (this._colorCurvesEnabled && this.colorCurves) {
  33695. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33696. }
  33697. // Vignette
  33698. if (this._vignetteEnabled) {
  33699. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33700. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33701. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33702. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33703. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33704. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33705. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33706. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33707. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33708. var vignettePower = -2.0 * this.vignetteWeight;
  33709. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33710. }
  33711. // Exposure
  33712. effect.setFloat("exposureLinear", this.exposure);
  33713. // Contrast
  33714. effect.setFloat("contrast", this.contrast);
  33715. // Color transform settings
  33716. if (this.colorGradingTexture) {
  33717. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33718. var textureSize = this.colorGradingTexture.getSize().height;
  33719. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33720. 0.5 / textureSize, // textureOffset
  33721. textureSize, // textureSize
  33722. this.colorGradingTexture.level // weight
  33723. );
  33724. }
  33725. };
  33726. /**
  33727. * Clones the current image processing instance.
  33728. * @return The cloned image processing
  33729. */
  33730. ImageProcessingConfiguration.prototype.clone = function () {
  33731. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33732. };
  33733. /**
  33734. * Serializes the current image processing instance to a json representation.
  33735. * @return a JSON representation
  33736. */
  33737. ImageProcessingConfiguration.prototype.serialize = function () {
  33738. return BABYLON.SerializationHelper.Serialize(this);
  33739. };
  33740. /**
  33741. * Parses the image processing from a json representation.
  33742. * @param source the JSON source to parse
  33743. * @return The parsed image processing
  33744. */
  33745. ImageProcessingConfiguration.Parse = function (source) {
  33746. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33747. };
  33748. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33749. /**
  33750. * Used to apply the vignette as a mix with the pixel color.
  33751. */
  33752. get: function () {
  33753. return this._VIGNETTEMODE_MULTIPLY;
  33754. },
  33755. enumerable: true,
  33756. configurable: true
  33757. });
  33758. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33759. /**
  33760. * Used to apply the vignette as a replacement of the pixel color.
  33761. */
  33762. get: function () {
  33763. return this._VIGNETTEMODE_OPAQUE;
  33764. },
  33765. enumerable: true,
  33766. configurable: true
  33767. });
  33768. // Static constants associated to the image processing.
  33769. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33770. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33771. __decorate([
  33772. BABYLON.serializeAsColorCurves()
  33773. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33774. __decorate([
  33775. BABYLON.serialize()
  33776. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33777. __decorate([
  33778. BABYLON.serializeAsTexture()
  33779. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33780. __decorate([
  33781. BABYLON.serialize()
  33782. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33783. __decorate([
  33784. BABYLON.serialize()
  33785. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33786. __decorate([
  33787. BABYLON.serialize()
  33788. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33789. __decorate([
  33790. BABYLON.serialize()
  33791. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33792. __decorate([
  33793. BABYLON.serialize()
  33794. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33795. __decorate([
  33796. BABYLON.serialize()
  33797. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33798. __decorate([
  33799. BABYLON.serialize()
  33800. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33801. __decorate([
  33802. BABYLON.serialize()
  33803. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33804. __decorate([
  33805. BABYLON.serialize()
  33806. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33807. __decorate([
  33808. BABYLON.serialize()
  33809. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33810. __decorate([
  33811. BABYLON.serializeAsColor4()
  33812. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33813. __decorate([
  33814. BABYLON.serialize()
  33815. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33816. __decorate([
  33817. BABYLON.serialize()
  33818. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33819. __decorate([
  33820. BABYLON.serialize()
  33821. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33822. __decorate([
  33823. BABYLON.serialize()
  33824. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33825. __decorate([
  33826. BABYLON.serialize()
  33827. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33828. return ImageProcessingConfiguration;
  33829. }());
  33830. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33831. })(BABYLON || (BABYLON = {}));
  33832. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33833. var BABYLON;
  33834. (function (BABYLON) {
  33835. /**
  33836. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33837. * It can help converting any input color in a desired output one. This can then be used to create effects
  33838. * from sepia, black and white to sixties or futuristic rendering...
  33839. *
  33840. * The only supported format is currently 3dl.
  33841. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33842. */
  33843. var ColorGradingTexture = /** @class */ (function (_super) {
  33844. __extends(ColorGradingTexture, _super);
  33845. /**
  33846. * Instantiates a ColorGradingTexture from the following parameters.
  33847. *
  33848. * @param url The location of the color gradind data (currently only supporting 3dl)
  33849. * @param scene The scene the texture will be used in
  33850. */
  33851. function ColorGradingTexture(url, scene) {
  33852. var _this = _super.call(this, scene) || this;
  33853. if (!url) {
  33854. return _this;
  33855. }
  33856. _this._engine = scene.getEngine();
  33857. _this._textureMatrix = BABYLON.Matrix.Identity();
  33858. _this.name = url;
  33859. _this.url = url;
  33860. _this.hasAlpha = false;
  33861. _this.isCube = false;
  33862. _this.is3D = _this._engine.webGLVersion > 1;
  33863. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33864. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33865. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33866. _this.anisotropicFilteringLevel = 1;
  33867. _this._texture = _this._getFromCache(url, true);
  33868. if (!_this._texture) {
  33869. if (!scene.useDelayedTextureLoading) {
  33870. _this.loadTexture();
  33871. }
  33872. else {
  33873. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33874. }
  33875. }
  33876. return _this;
  33877. }
  33878. /**
  33879. * Returns the texture matrix used in most of the material.
  33880. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33881. */
  33882. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33883. return this._textureMatrix;
  33884. };
  33885. /**
  33886. * Occurs when the file being loaded is a .3dl LUT file.
  33887. */
  33888. ColorGradingTexture.prototype.load3dlTexture = function () {
  33889. var engine = this._engine;
  33890. var texture;
  33891. if (engine.webGLVersion === 1) {
  33892. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33893. }
  33894. else {
  33895. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33896. }
  33897. this._texture = texture;
  33898. var callback = function (text) {
  33899. if (typeof text !== "string") {
  33900. return;
  33901. }
  33902. var data = null;
  33903. var tempData = null;
  33904. var line;
  33905. var lines = text.split('\n');
  33906. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33907. var maxColor = 0;
  33908. for (var i = 0; i < lines.length; i++) {
  33909. line = lines[i];
  33910. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33911. continue;
  33912. if (line.indexOf('#') === 0)
  33913. continue;
  33914. var words = line.split(" ");
  33915. if (size === 0) {
  33916. // Number of space + one
  33917. size = words.length;
  33918. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33919. tempData = new Float32Array(size * size * size * 4);
  33920. continue;
  33921. }
  33922. if (size != 0) {
  33923. var r = Math.max(parseInt(words[0]), 0);
  33924. var g = Math.max(parseInt(words[1]), 0);
  33925. var b = Math.max(parseInt(words[2]), 0);
  33926. maxColor = Math.max(r, maxColor);
  33927. maxColor = Math.max(g, maxColor);
  33928. maxColor = Math.max(b, maxColor);
  33929. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33930. if (tempData) {
  33931. tempData[pixelStorageIndex + 0] = r;
  33932. tempData[pixelStorageIndex + 1] = g;
  33933. tempData[pixelStorageIndex + 2] = b;
  33934. }
  33935. pixelIndexSlice++;
  33936. if (pixelIndexSlice % size == 0) {
  33937. pixelIndexH++;
  33938. pixelIndexSlice = 0;
  33939. if (pixelIndexH % size == 0) {
  33940. pixelIndexW++;
  33941. pixelIndexH = 0;
  33942. }
  33943. }
  33944. }
  33945. }
  33946. if (tempData && data) {
  33947. for (var i = 0; i < tempData.length; i++) {
  33948. if (i > 0 && (i + 1) % 4 === 0) {
  33949. data[i] = 255;
  33950. }
  33951. else {
  33952. var value = tempData[i];
  33953. data[i] = (value / maxColor * 255);
  33954. }
  33955. }
  33956. }
  33957. if (texture.is3D) {
  33958. texture.updateSize(size, size, size);
  33959. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33960. }
  33961. else {
  33962. texture.updateSize(size * size, size);
  33963. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33964. }
  33965. };
  33966. var scene = this.getScene();
  33967. if (scene) {
  33968. scene._loadFile(this.url, callback);
  33969. }
  33970. else {
  33971. this._engine._loadFile(this.url, callback);
  33972. }
  33973. return this._texture;
  33974. };
  33975. /**
  33976. * Starts the loading process of the texture.
  33977. */
  33978. ColorGradingTexture.prototype.loadTexture = function () {
  33979. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33980. this.load3dlTexture();
  33981. }
  33982. };
  33983. /**
  33984. * Clones the color gradind texture.
  33985. */
  33986. ColorGradingTexture.prototype.clone = function () {
  33987. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33988. // Base texture
  33989. newTexture.level = this.level;
  33990. return newTexture;
  33991. };
  33992. /**
  33993. * Called during delayed load for textures.
  33994. */
  33995. ColorGradingTexture.prototype.delayLoad = function () {
  33996. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33997. return;
  33998. }
  33999. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34000. this._texture = this._getFromCache(this.url, true);
  34001. if (!this._texture) {
  34002. this.loadTexture();
  34003. }
  34004. };
  34005. /**
  34006. * Parses a color grading texture serialized by Babylon.
  34007. * @param parsedTexture The texture information being parsedTexture
  34008. * @param scene The scene to load the texture in
  34009. * @param rootUrl The root url of the data assets to load
  34010. * @return A color gradind texture
  34011. */
  34012. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  34013. var texture = null;
  34014. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  34015. texture = new ColorGradingTexture(parsedTexture.name, scene);
  34016. texture.name = parsedTexture.name;
  34017. texture.level = parsedTexture.level;
  34018. }
  34019. return texture;
  34020. };
  34021. /**
  34022. * Serializes the LUT texture to json format.
  34023. */
  34024. ColorGradingTexture.prototype.serialize = function () {
  34025. if (!this.name) {
  34026. return null;
  34027. }
  34028. var serializationObject = {};
  34029. serializationObject.name = this.name;
  34030. serializationObject.level = this.level;
  34031. serializationObject.customType = "BABYLON.ColorGradingTexture";
  34032. return serializationObject;
  34033. };
  34034. /**
  34035. * Empty line regex stored for GC.
  34036. */
  34037. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  34038. return ColorGradingTexture;
  34039. }(BABYLON.BaseTexture));
  34040. BABYLON.ColorGradingTexture = ColorGradingTexture;
  34041. })(BABYLON || (BABYLON = {}));
  34042. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  34043. var BABYLON;
  34044. (function (BABYLON) {
  34045. /**
  34046. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34047. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34048. * 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;
  34049. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34050. */
  34051. var ColorCurves = /** @class */ (function () {
  34052. function ColorCurves() {
  34053. this._dirty = true;
  34054. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  34055. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  34056. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  34057. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  34058. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  34059. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  34060. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  34061. this._globalHue = 30;
  34062. this._globalDensity = 0;
  34063. this._globalSaturation = 0;
  34064. this._globalExposure = 0;
  34065. this._highlightsHue = 30;
  34066. this._highlightsDensity = 0;
  34067. this._highlightsSaturation = 0;
  34068. this._highlightsExposure = 0;
  34069. this._midtonesHue = 30;
  34070. this._midtonesDensity = 0;
  34071. this._midtonesSaturation = 0;
  34072. this._midtonesExposure = 0;
  34073. this._shadowsHue = 30;
  34074. this._shadowsDensity = 0;
  34075. this._shadowsSaturation = 0;
  34076. this._shadowsExposure = 0;
  34077. }
  34078. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  34079. /**
  34080. * Gets the global Hue value.
  34081. * 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).
  34082. */
  34083. get: function () {
  34084. return this._globalHue;
  34085. },
  34086. /**
  34087. * Sets the global Hue value.
  34088. * 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).
  34089. */
  34090. set: function (value) {
  34091. this._globalHue = value;
  34092. this._dirty = true;
  34093. },
  34094. enumerable: true,
  34095. configurable: true
  34096. });
  34097. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  34098. /**
  34099. * Gets the global Density value.
  34100. * 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.
  34101. * Values less than zero provide a filter of opposite hue.
  34102. */
  34103. get: function () {
  34104. return this._globalDensity;
  34105. },
  34106. /**
  34107. * Sets the global Density value.
  34108. * 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.
  34109. * Values less than zero provide a filter of opposite hue.
  34110. */
  34111. set: function (value) {
  34112. this._globalDensity = value;
  34113. this._dirty = true;
  34114. },
  34115. enumerable: true,
  34116. configurable: true
  34117. });
  34118. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  34119. /**
  34120. * Gets the global Saturation value.
  34121. * 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.
  34122. */
  34123. get: function () {
  34124. return this._globalSaturation;
  34125. },
  34126. /**
  34127. * Sets the global Saturation value.
  34128. * 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.
  34129. */
  34130. set: function (value) {
  34131. this._globalSaturation = value;
  34132. this._dirty = true;
  34133. },
  34134. enumerable: true,
  34135. configurable: true
  34136. });
  34137. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  34138. /**
  34139. * Gets the highlights Hue value.
  34140. * 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).
  34141. */
  34142. get: function () {
  34143. return this._highlightsHue;
  34144. },
  34145. /**
  34146. * Sets the highlights Hue value.
  34147. * 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).
  34148. */
  34149. set: function (value) {
  34150. this._highlightsHue = value;
  34151. this._dirty = true;
  34152. },
  34153. enumerable: true,
  34154. configurable: true
  34155. });
  34156. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  34157. /**
  34158. * Gets the highlights Density value.
  34159. * 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.
  34160. * Values less than zero provide a filter of opposite hue.
  34161. */
  34162. get: function () {
  34163. return this._highlightsDensity;
  34164. },
  34165. /**
  34166. * Sets the highlights Density value.
  34167. * 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.
  34168. * Values less than zero provide a filter of opposite hue.
  34169. */
  34170. set: function (value) {
  34171. this._highlightsDensity = value;
  34172. this._dirty = true;
  34173. },
  34174. enumerable: true,
  34175. configurable: true
  34176. });
  34177. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  34178. /**
  34179. * Gets the highlights Saturation value.
  34180. * 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.
  34181. */
  34182. get: function () {
  34183. return this._highlightsSaturation;
  34184. },
  34185. /**
  34186. * Sets the highlights Saturation value.
  34187. * 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.
  34188. */
  34189. set: function (value) {
  34190. this._highlightsSaturation = value;
  34191. this._dirty = true;
  34192. },
  34193. enumerable: true,
  34194. configurable: true
  34195. });
  34196. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  34197. /**
  34198. * Gets the highlights Exposure value.
  34199. * 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.
  34200. */
  34201. get: function () {
  34202. return this._highlightsExposure;
  34203. },
  34204. /**
  34205. * Sets the highlights Exposure value.
  34206. * 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.
  34207. */
  34208. set: function (value) {
  34209. this._highlightsExposure = value;
  34210. this._dirty = true;
  34211. },
  34212. enumerable: true,
  34213. configurable: true
  34214. });
  34215. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  34216. /**
  34217. * Gets the midtones Hue value.
  34218. * 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).
  34219. */
  34220. get: function () {
  34221. return this._midtonesHue;
  34222. },
  34223. /**
  34224. * Sets the midtones Hue value.
  34225. * 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).
  34226. */
  34227. set: function (value) {
  34228. this._midtonesHue = value;
  34229. this._dirty = true;
  34230. },
  34231. enumerable: true,
  34232. configurable: true
  34233. });
  34234. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  34235. /**
  34236. * Gets the midtones Density value.
  34237. * 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.
  34238. * Values less than zero provide a filter of opposite hue.
  34239. */
  34240. get: function () {
  34241. return this._midtonesDensity;
  34242. },
  34243. /**
  34244. * Sets the midtones Density value.
  34245. * 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.
  34246. * Values less than zero provide a filter of opposite hue.
  34247. */
  34248. set: function (value) {
  34249. this._midtonesDensity = value;
  34250. this._dirty = true;
  34251. },
  34252. enumerable: true,
  34253. configurable: true
  34254. });
  34255. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  34256. /**
  34257. * Gets the midtones Saturation value.
  34258. * 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.
  34259. */
  34260. get: function () {
  34261. return this._midtonesSaturation;
  34262. },
  34263. /**
  34264. * Sets the midtones Saturation value.
  34265. * 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.
  34266. */
  34267. set: function (value) {
  34268. this._midtonesSaturation = value;
  34269. this._dirty = true;
  34270. },
  34271. enumerable: true,
  34272. configurable: true
  34273. });
  34274. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  34275. /**
  34276. * Gets the midtones Exposure value.
  34277. * 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.
  34278. */
  34279. get: function () {
  34280. return this._midtonesExposure;
  34281. },
  34282. /**
  34283. * Sets the midtones Exposure value.
  34284. * 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.
  34285. */
  34286. set: function (value) {
  34287. this._midtonesExposure = value;
  34288. this._dirty = true;
  34289. },
  34290. enumerable: true,
  34291. configurable: true
  34292. });
  34293. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  34294. /**
  34295. * Gets the shadows Hue value.
  34296. * 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).
  34297. */
  34298. get: function () {
  34299. return this._shadowsHue;
  34300. },
  34301. /**
  34302. * Sets the shadows Hue value.
  34303. * 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).
  34304. */
  34305. set: function (value) {
  34306. this._shadowsHue = value;
  34307. this._dirty = true;
  34308. },
  34309. enumerable: true,
  34310. configurable: true
  34311. });
  34312. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  34313. /**
  34314. * Gets the shadows Density value.
  34315. * 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.
  34316. * Values less than zero provide a filter of opposite hue.
  34317. */
  34318. get: function () {
  34319. return this._shadowsDensity;
  34320. },
  34321. /**
  34322. * Sets the shadows Density value.
  34323. * 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.
  34324. * Values less than zero provide a filter of opposite hue.
  34325. */
  34326. set: function (value) {
  34327. this._shadowsDensity = value;
  34328. this._dirty = true;
  34329. },
  34330. enumerable: true,
  34331. configurable: true
  34332. });
  34333. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  34334. /**
  34335. * Gets the shadows Saturation value.
  34336. * 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.
  34337. */
  34338. get: function () {
  34339. return this._shadowsSaturation;
  34340. },
  34341. /**
  34342. * Sets the shadows Saturation value.
  34343. * 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.
  34344. */
  34345. set: function (value) {
  34346. this._shadowsSaturation = value;
  34347. this._dirty = true;
  34348. },
  34349. enumerable: true,
  34350. configurable: true
  34351. });
  34352. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  34353. /**
  34354. * Gets the shadows Exposure value.
  34355. * 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.
  34356. */
  34357. get: function () {
  34358. return this._shadowsExposure;
  34359. },
  34360. /**
  34361. * Sets the shadows Exposure value.
  34362. * 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.
  34363. */
  34364. set: function (value) {
  34365. this._shadowsExposure = value;
  34366. this._dirty = true;
  34367. },
  34368. enumerable: true,
  34369. configurable: true
  34370. });
  34371. ColorCurves.prototype.getClassName = function () {
  34372. return "ColorCurves";
  34373. };
  34374. /**
  34375. * Binds the color curves to the shader.
  34376. * @param colorCurves The color curve to bind
  34377. * @param effect The effect to bind to
  34378. */
  34379. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  34380. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  34381. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  34382. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  34383. if (colorCurves._dirty) {
  34384. colorCurves._dirty = false;
  34385. // Fill in global info.
  34386. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  34387. // Compute highlights info.
  34388. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  34389. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  34390. // Compute midtones info.
  34391. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  34392. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  34393. // Compute shadows info.
  34394. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  34395. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  34396. // Compute deltas (neutral is midtones).
  34397. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  34398. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  34399. }
  34400. if (effect) {
  34401. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  34402. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  34403. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  34404. }
  34405. };
  34406. /**
  34407. * Prepare the list of uniforms associated with the ColorCurves effects.
  34408. * @param uniformsList The list of uniforms used in the effect
  34409. */
  34410. ColorCurves.PrepareUniforms = function (uniformsList) {
  34411. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  34412. };
  34413. /**
  34414. * Returns color grading data based on a hue, density, saturation and exposure value.
  34415. * @param filterHue The hue of the color filter.
  34416. * @param filterDensity The density of the color filter.
  34417. * @param saturation The saturation.
  34418. * @param exposure The exposure.
  34419. * @param result The result data container.
  34420. */
  34421. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  34422. if (hue == null) {
  34423. return;
  34424. }
  34425. hue = ColorCurves.clamp(hue, 0, 360);
  34426. density = ColorCurves.clamp(density, -100, 100);
  34427. saturation = ColorCurves.clamp(saturation, -100, 100);
  34428. exposure = ColorCurves.clamp(exposure, -100, 100);
  34429. // Remap the slider/config filter density with non-linear mapping and also scale by half
  34430. // so that the maximum filter density is only 50% control. This provides fine control
  34431. // for small values and reasonable range.
  34432. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  34433. density *= 0.5;
  34434. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  34435. if (density < 0) {
  34436. density *= -1;
  34437. hue = (hue + 180) % 360;
  34438. }
  34439. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  34440. result.scaleToRef(2, result);
  34441. result.a = 1 + 0.01 * saturation;
  34442. };
  34443. /**
  34444. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  34445. * @param value The input slider value in range [-100,100].
  34446. * @returns Adjusted value.
  34447. */
  34448. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  34449. value /= 100;
  34450. var x = Math.abs(value);
  34451. x = Math.pow(x, 2);
  34452. if (value < 0) {
  34453. x *= -1;
  34454. }
  34455. x *= 100;
  34456. return x;
  34457. };
  34458. /**
  34459. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  34460. * @param hue The hue (H) input.
  34461. * @param saturation The saturation (S) input.
  34462. * @param brightness The brightness (B) input.
  34463. * @result An RGBA color represented as Vector4.
  34464. */
  34465. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  34466. var h = ColorCurves.clamp(hue, 0, 360);
  34467. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  34468. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  34469. if (s === 0) {
  34470. result.r = v;
  34471. result.g = v;
  34472. result.b = v;
  34473. }
  34474. else {
  34475. // sector 0 to 5
  34476. h /= 60;
  34477. var i = Math.floor(h);
  34478. // fractional part of h
  34479. var f = h - i;
  34480. var p = v * (1 - s);
  34481. var q = v * (1 - s * f);
  34482. var t = v * (1 - s * (1 - f));
  34483. switch (i) {
  34484. case 0:
  34485. result.r = v;
  34486. result.g = t;
  34487. result.b = p;
  34488. break;
  34489. case 1:
  34490. result.r = q;
  34491. result.g = v;
  34492. result.b = p;
  34493. break;
  34494. case 2:
  34495. result.r = p;
  34496. result.g = v;
  34497. result.b = t;
  34498. break;
  34499. case 3:
  34500. result.r = p;
  34501. result.g = q;
  34502. result.b = v;
  34503. break;
  34504. case 4:
  34505. result.r = t;
  34506. result.g = p;
  34507. result.b = v;
  34508. break;
  34509. default:// case 5:
  34510. result.r = v;
  34511. result.g = p;
  34512. result.b = q;
  34513. break;
  34514. }
  34515. }
  34516. result.a = 1;
  34517. };
  34518. /**
  34519. * Returns a value clamped between min and max
  34520. * @param value The value to clamp
  34521. * @param min The minimum of value
  34522. * @param max The maximum of value
  34523. * @returns The clamped value.
  34524. */
  34525. ColorCurves.clamp = function (value, min, max) {
  34526. return Math.min(Math.max(value, min), max);
  34527. };
  34528. /**
  34529. * Clones the current color curve instance.
  34530. * @return The cloned curves
  34531. */
  34532. ColorCurves.prototype.clone = function () {
  34533. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  34534. };
  34535. /**
  34536. * Serializes the current color curve instance to a json representation.
  34537. * @return a JSON representation
  34538. */
  34539. ColorCurves.prototype.serialize = function () {
  34540. return BABYLON.SerializationHelper.Serialize(this);
  34541. };
  34542. /**
  34543. * Parses the color curve from a json representation.
  34544. * @param source the JSON source to parse
  34545. * @return The parsed curves
  34546. */
  34547. ColorCurves.Parse = function (source) {
  34548. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  34549. };
  34550. __decorate([
  34551. BABYLON.serialize()
  34552. ], ColorCurves.prototype, "_globalHue", void 0);
  34553. __decorate([
  34554. BABYLON.serialize()
  34555. ], ColorCurves.prototype, "_globalDensity", void 0);
  34556. __decorate([
  34557. BABYLON.serialize()
  34558. ], ColorCurves.prototype, "_globalSaturation", void 0);
  34559. __decorate([
  34560. BABYLON.serialize()
  34561. ], ColorCurves.prototype, "_globalExposure", void 0);
  34562. __decorate([
  34563. BABYLON.serialize()
  34564. ], ColorCurves.prototype, "_highlightsHue", void 0);
  34565. __decorate([
  34566. BABYLON.serialize()
  34567. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  34568. __decorate([
  34569. BABYLON.serialize()
  34570. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  34571. __decorate([
  34572. BABYLON.serialize()
  34573. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  34574. __decorate([
  34575. BABYLON.serialize()
  34576. ], ColorCurves.prototype, "_midtonesHue", void 0);
  34577. __decorate([
  34578. BABYLON.serialize()
  34579. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  34580. __decorate([
  34581. BABYLON.serialize()
  34582. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  34583. __decorate([
  34584. BABYLON.serialize()
  34585. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  34586. return ColorCurves;
  34587. }());
  34588. BABYLON.ColorCurves = ColorCurves;
  34589. })(BABYLON || (BABYLON = {}));
  34590. //# sourceMappingURL=babylon.colorCurves.js.map
  34591. //# sourceMappingURL=babylon.behavior.js.map
  34592. var BABYLON;
  34593. (function (BABYLON) {
  34594. var MaterialHelper = /** @class */ (function () {
  34595. function MaterialHelper() {
  34596. }
  34597. MaterialHelper.BindEyePosition = function (effect, scene) {
  34598. if (scene._forcedViewPosition) {
  34599. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  34600. return;
  34601. }
  34602. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  34603. };
  34604. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  34605. defines._needUVs = true;
  34606. defines[key] = true;
  34607. if (texture.getTextureMatrix().isIdentity(true)) {
  34608. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  34609. if (texture.coordinatesIndex === 0) {
  34610. defines["MAINUV1"] = true;
  34611. }
  34612. else {
  34613. defines["MAINUV2"] = true;
  34614. }
  34615. }
  34616. else {
  34617. defines[key + "DIRECTUV"] = 0;
  34618. }
  34619. };
  34620. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  34621. var matrix = texture.getTextureMatrix();
  34622. if (!matrix.isIdentity(true)) {
  34623. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  34624. }
  34625. };
  34626. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  34627. if (defines._areMiscDirty) {
  34628. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  34629. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  34630. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  34631. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  34632. }
  34633. };
  34634. /**
  34635. * Helper used to prepare the list of defines for shader compilation
  34636. * @param scene defines the current scene
  34637. * @param engine defines the current engine
  34638. * @param defines specifies the list of active defines
  34639. * @param useInstances defines if instances have to be turned on
  34640. * @param alphaTest defines if alpha testing has to be turned on
  34641. */
  34642. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, alphaTest) {
  34643. var changed = false;
  34644. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  34645. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  34646. changed = true;
  34647. }
  34648. if (defines["ALPHATEST"] !== alphaTest) {
  34649. defines["ALPHATEST"] = !defines["ALPHATEST"];
  34650. changed = true;
  34651. }
  34652. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  34653. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  34654. changed = true;
  34655. }
  34656. if (defines["INSTANCES"] !== useInstances) {
  34657. defines["INSTANCES"] = useInstances;
  34658. changed = true;
  34659. }
  34660. if (changed) {
  34661. defines.markAsUnprocessed();
  34662. }
  34663. };
  34664. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  34665. if (useMorphTargets === void 0) { useMorphTargets = false; }
  34666. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  34667. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  34668. return false;
  34669. }
  34670. defines._normals = defines._needNormals;
  34671. defines._uvs = defines._needUVs;
  34672. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  34673. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34674. defines["TANGENT"] = true;
  34675. }
  34676. if (defines._needUVs) {
  34677. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  34678. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  34679. }
  34680. else {
  34681. defines["UV1"] = false;
  34682. defines["UV2"] = false;
  34683. }
  34684. if (useVertexColor) {
  34685. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  34686. defines["VERTEXCOLOR"] = hasVertexColors;
  34687. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  34688. }
  34689. if (useBones) {
  34690. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34691. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  34692. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  34693. }
  34694. else {
  34695. defines["NUM_BONE_INFLUENCERS"] = 0;
  34696. defines["BonesPerMesh"] = 0;
  34697. }
  34698. }
  34699. if (useMorphTargets) {
  34700. var manager = mesh.morphTargetManager;
  34701. if (manager) {
  34702. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  34703. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  34704. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  34705. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  34706. }
  34707. else {
  34708. defines["MORPHTARGETS_TANGENT"] = false;
  34709. defines["MORPHTARGETS_NORMAL"] = false;
  34710. defines["MORPHTARGETS"] = false;
  34711. defines["NUM_MORPH_INFLUENCERS"] = 0;
  34712. }
  34713. }
  34714. return true;
  34715. };
  34716. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  34717. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34718. if (disableLighting === void 0) { disableLighting = false; }
  34719. if (!defines._areLightsDirty) {
  34720. return defines._needNormals;
  34721. }
  34722. var lightIndex = 0;
  34723. var needNormals = false;
  34724. var needRebuild = false;
  34725. var lightmapMode = false;
  34726. var shadowEnabled = false;
  34727. var specularEnabled = false;
  34728. if (scene.lightsEnabled && !disableLighting) {
  34729. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34730. var light = _a[_i];
  34731. needNormals = true;
  34732. if (defines["LIGHT" + lightIndex] === undefined) {
  34733. needRebuild = true;
  34734. }
  34735. defines["LIGHT" + lightIndex] = true;
  34736. defines["SPOTLIGHT" + lightIndex] = false;
  34737. defines["HEMILIGHT" + lightIndex] = false;
  34738. defines["POINTLIGHT" + lightIndex] = false;
  34739. defines["DIRLIGHT" + lightIndex] = false;
  34740. var type;
  34741. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  34742. type = "SPOTLIGHT" + lightIndex;
  34743. }
  34744. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  34745. type = "HEMILIGHT" + lightIndex;
  34746. }
  34747. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  34748. type = "POINTLIGHT" + lightIndex;
  34749. }
  34750. else {
  34751. type = "DIRLIGHT" + lightIndex;
  34752. }
  34753. defines[type] = true;
  34754. // Specular
  34755. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  34756. specularEnabled = true;
  34757. }
  34758. // Shadows
  34759. defines["SHADOW" + lightIndex] = false;
  34760. defines["SHADOWPCF" + lightIndex] = false;
  34761. defines["SHADOWESM" + lightIndex] = false;
  34762. defines["SHADOWCUBE" + lightIndex] = false;
  34763. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  34764. var shadowGenerator = light.getShadowGenerator();
  34765. if (shadowGenerator) {
  34766. shadowEnabled = true;
  34767. shadowGenerator.prepareDefines(defines, lightIndex);
  34768. }
  34769. }
  34770. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  34771. lightmapMode = true;
  34772. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  34773. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  34774. }
  34775. else {
  34776. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  34777. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  34778. }
  34779. lightIndex++;
  34780. if (lightIndex === maxSimultaneousLights)
  34781. break;
  34782. }
  34783. }
  34784. defines["SPECULARTERM"] = specularEnabled;
  34785. defines["SHADOWS"] = shadowEnabled;
  34786. // Resetting all other lights if any
  34787. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  34788. if (defines["LIGHT" + index] !== undefined) {
  34789. defines["LIGHT" + index] = false;
  34790. defines["HEMILIGHT" + lightIndex] = false;
  34791. defines["POINTLIGHT" + lightIndex] = false;
  34792. defines["DIRLIGHT" + lightIndex] = false;
  34793. defines["SPOTLIGHT" + lightIndex] = false;
  34794. defines["SHADOW" + lightIndex] = false;
  34795. }
  34796. }
  34797. var caps = scene.getEngine().getCaps();
  34798. if (defines["SHADOWFLOAT"] === undefined) {
  34799. needRebuild = true;
  34800. }
  34801. defines["SHADOWFLOAT"] = shadowEnabled &&
  34802. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  34803. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  34804. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  34805. if (needRebuild) {
  34806. defines.rebuild();
  34807. }
  34808. return needNormals;
  34809. };
  34810. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  34811. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34812. var uniformsList;
  34813. var uniformBuffersList = null;
  34814. if (uniformsListOrOptions.uniformsNames) {
  34815. var options = uniformsListOrOptions;
  34816. uniformsList = options.uniformsNames;
  34817. uniformBuffersList = options.uniformBuffersNames;
  34818. samplersList = options.samplers;
  34819. defines = options.defines;
  34820. maxSimultaneousLights = options.maxSimultaneousLights;
  34821. }
  34822. else {
  34823. uniformsList = uniformsListOrOptions;
  34824. if (!samplersList) {
  34825. samplersList = [];
  34826. }
  34827. }
  34828. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34829. if (!defines["LIGHT" + lightIndex]) {
  34830. break;
  34831. }
  34832. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  34833. if (uniformBuffersList) {
  34834. uniformBuffersList.push("Light" + lightIndex);
  34835. }
  34836. samplersList.push("shadowSampler" + lightIndex);
  34837. }
  34838. if (defines["NUM_MORPH_INFLUENCERS"]) {
  34839. uniformsList.push("morphTargetInfluences");
  34840. }
  34841. };
  34842. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  34843. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34844. if (rank === void 0) { rank = 0; }
  34845. var lightFallbackRank = 0;
  34846. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34847. if (!defines["LIGHT" + lightIndex]) {
  34848. break;
  34849. }
  34850. if (lightIndex > 0) {
  34851. lightFallbackRank = rank + lightIndex;
  34852. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  34853. }
  34854. if (!defines["SHADOWS"]) {
  34855. if (defines["SHADOW" + lightIndex]) {
  34856. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  34857. }
  34858. if (defines["SHADOWPCF" + lightIndex]) {
  34859. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  34860. }
  34861. if (defines["SHADOWESM" + lightIndex]) {
  34862. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  34863. }
  34864. }
  34865. }
  34866. return lightFallbackRank++;
  34867. };
  34868. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  34869. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  34870. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  34871. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  34872. var manager = mesh.morphTargetManager;
  34873. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  34874. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  34875. for (var index = 0; index < influencers; index++) {
  34876. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  34877. if (normal) {
  34878. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  34879. }
  34880. if (tangent) {
  34881. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  34882. }
  34883. if (attribs.length > maxAttributesCount) {
  34884. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  34885. }
  34886. }
  34887. }
  34888. };
  34889. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  34890. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  34891. fallbacks.addCPUSkinningFallback(0, mesh);
  34892. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34893. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34894. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  34895. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34896. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34897. }
  34898. }
  34899. };
  34900. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  34901. if (defines["INSTANCES"]) {
  34902. attribs.push("world0");
  34903. attribs.push("world1");
  34904. attribs.push("world2");
  34905. attribs.push("world3");
  34906. }
  34907. };
  34908. // Bindings
  34909. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  34910. if (light.shadowEnabled && mesh.receiveShadows) {
  34911. var shadowGenerator = light.getShadowGenerator();
  34912. if (shadowGenerator) {
  34913. shadowGenerator.bindShadowLight(lightIndex, effect);
  34914. }
  34915. }
  34916. };
  34917. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  34918. light.transferToEffect(effect, lightIndex + "");
  34919. };
  34920. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  34921. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34922. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  34923. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  34924. for (var i = 0; i < len; i++) {
  34925. var light = mesh._lightSources[i];
  34926. var iAsString = i.toString();
  34927. var scaledIntensity = light.getScaledIntensity();
  34928. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  34929. MaterialHelper.BindLightProperties(light, effect, i);
  34930. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  34931. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  34932. if (defines["SPECULARTERM"]) {
  34933. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  34934. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  34935. }
  34936. // Shadows
  34937. if (scene.shadowsEnabled) {
  34938. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  34939. }
  34940. light._uniformBuffer.update();
  34941. }
  34942. };
  34943. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  34944. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34945. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34946. effect.setColor3("vFogColor", scene.fogColor);
  34947. }
  34948. };
  34949. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  34950. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34951. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  34952. if (matrices && effect) {
  34953. effect.setMatrices("mBones", matrices);
  34954. }
  34955. }
  34956. };
  34957. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  34958. var manager = abstractMesh.morphTargetManager;
  34959. if (!abstractMesh || !manager) {
  34960. return;
  34961. }
  34962. effect.setFloatArray("morphTargetInfluences", manager.influences);
  34963. };
  34964. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  34965. if (defines["LOGARITHMICDEPTH"]) {
  34966. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  34967. }
  34968. };
  34969. MaterialHelper.BindClipPlane = function (effect, scene) {
  34970. if (scene.clipPlane) {
  34971. var clipPlane = scene.clipPlane;
  34972. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34973. }
  34974. };
  34975. return MaterialHelper;
  34976. }());
  34977. BABYLON.MaterialHelper = MaterialHelper;
  34978. })(BABYLON || (BABYLON = {}));
  34979. //# sourceMappingURL=babylon.materialHelper.js.map
  34980. var BABYLON;
  34981. (function (BABYLON) {
  34982. var PushMaterial = /** @class */ (function (_super) {
  34983. __extends(PushMaterial, _super);
  34984. function PushMaterial(name, scene) {
  34985. var _this = _super.call(this, name, scene) || this;
  34986. _this.storeEffectOnSubMeshes = true;
  34987. return _this;
  34988. }
  34989. PushMaterial.prototype.getEffect = function () {
  34990. return this._activeEffect;
  34991. };
  34992. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  34993. if (!mesh) {
  34994. return false;
  34995. }
  34996. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  34997. return true;
  34998. }
  34999. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  35000. };
  35001. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35002. this._activeEffect.setMatrix("world", world);
  35003. };
  35004. PushMaterial.prototype.bind = function (world, mesh) {
  35005. if (!mesh) {
  35006. return;
  35007. }
  35008. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  35009. };
  35010. PushMaterial.prototype._afterBind = function (mesh, effect) {
  35011. if (effect === void 0) { effect = null; }
  35012. _super.prototype._afterBind.call(this, mesh);
  35013. this.getScene()._cachedEffect = effect;
  35014. };
  35015. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  35016. if (visibility === void 0) { visibility = 1; }
  35017. return scene.isCachedMaterialInvalid(this, effect, visibility);
  35018. };
  35019. return PushMaterial;
  35020. }(BABYLON.Material));
  35021. BABYLON.PushMaterial = PushMaterial;
  35022. })(BABYLON || (BABYLON = {}));
  35023. //# sourceMappingURL=babylon.pushMaterial.js.map
  35024. var BABYLON;
  35025. (function (BABYLON) {
  35026. var StandardMaterialDefines = /** @class */ (function (_super) {
  35027. __extends(StandardMaterialDefines, _super);
  35028. function StandardMaterialDefines() {
  35029. var _this = _super.call(this) || this;
  35030. _this.MAINUV1 = false;
  35031. _this.MAINUV2 = false;
  35032. _this.DIFFUSE = false;
  35033. _this.DIFFUSEDIRECTUV = 0;
  35034. _this.AMBIENT = false;
  35035. _this.AMBIENTDIRECTUV = 0;
  35036. _this.OPACITY = false;
  35037. _this.OPACITYDIRECTUV = 0;
  35038. _this.OPACITYRGB = false;
  35039. _this.REFLECTION = false;
  35040. _this.EMISSIVE = false;
  35041. _this.EMISSIVEDIRECTUV = 0;
  35042. _this.SPECULAR = false;
  35043. _this.SPECULARDIRECTUV = 0;
  35044. _this.BUMP = false;
  35045. _this.BUMPDIRECTUV = 0;
  35046. _this.PARALLAX = false;
  35047. _this.PARALLAXOCCLUSION = false;
  35048. _this.SPECULAROVERALPHA = false;
  35049. _this.CLIPPLANE = false;
  35050. _this.ALPHATEST = false;
  35051. _this.DEPTHPREPASS = false;
  35052. _this.ALPHAFROMDIFFUSE = false;
  35053. _this.POINTSIZE = false;
  35054. _this.FOG = false;
  35055. _this.SPECULARTERM = false;
  35056. _this.DIFFUSEFRESNEL = false;
  35057. _this.OPACITYFRESNEL = false;
  35058. _this.REFLECTIONFRESNEL = false;
  35059. _this.REFRACTIONFRESNEL = false;
  35060. _this.EMISSIVEFRESNEL = false;
  35061. _this.FRESNEL = false;
  35062. _this.NORMAL = false;
  35063. _this.UV1 = false;
  35064. _this.UV2 = false;
  35065. _this.VERTEXCOLOR = false;
  35066. _this.VERTEXALPHA = false;
  35067. _this.NUM_BONE_INFLUENCERS = 0;
  35068. _this.BonesPerMesh = 0;
  35069. _this.INSTANCES = false;
  35070. _this.GLOSSINESS = false;
  35071. _this.ROUGHNESS = false;
  35072. _this.EMISSIVEASILLUMINATION = false;
  35073. _this.LINKEMISSIVEWITHDIFFUSE = false;
  35074. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  35075. _this.LIGHTMAP = false;
  35076. _this.LIGHTMAPDIRECTUV = 0;
  35077. _this.USELIGHTMAPASSHADOWMAP = false;
  35078. _this.REFLECTIONMAP_3D = false;
  35079. _this.REFLECTIONMAP_SPHERICAL = false;
  35080. _this.REFLECTIONMAP_PLANAR = false;
  35081. _this.REFLECTIONMAP_CUBIC = false;
  35082. _this.REFLECTIONMAP_PROJECTION = false;
  35083. _this.REFLECTIONMAP_SKYBOX = false;
  35084. _this.REFLECTIONMAP_EXPLICIT = false;
  35085. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35086. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35087. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35088. _this.INVERTCUBICMAP = false;
  35089. _this.LOGARITHMICDEPTH = false;
  35090. _this.REFRACTION = false;
  35091. _this.REFRACTIONMAP_3D = false;
  35092. _this.REFLECTIONOVERALPHA = false;
  35093. _this.TWOSIDEDLIGHTING = false;
  35094. _this.SHADOWFLOAT = false;
  35095. _this.MORPHTARGETS = false;
  35096. _this.MORPHTARGETS_NORMAL = false;
  35097. _this.MORPHTARGETS_TANGENT = false;
  35098. _this.NUM_MORPH_INFLUENCERS = 0;
  35099. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  35100. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  35101. _this.IMAGEPROCESSING = false;
  35102. _this.VIGNETTE = false;
  35103. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35104. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35105. _this.TONEMAPPING = false;
  35106. _this.CONTRAST = false;
  35107. _this.COLORCURVES = false;
  35108. _this.COLORGRADING = false;
  35109. _this.COLORGRADING3D = false;
  35110. _this.SAMPLER3DGREENDEPTH = false;
  35111. _this.SAMPLER3DBGRMAP = false;
  35112. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35113. _this.EXPOSURE = false;
  35114. _this.rebuild();
  35115. return _this;
  35116. }
  35117. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  35118. var modes = [
  35119. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  35120. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  35121. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  35122. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  35123. ];
  35124. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  35125. var mode = modes_1[_i];
  35126. this[mode] = (mode === modeToEnable);
  35127. }
  35128. };
  35129. return StandardMaterialDefines;
  35130. }(BABYLON.MaterialDefines));
  35131. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  35132. var StandardMaterial = /** @class */ (function (_super) {
  35133. __extends(StandardMaterial, _super);
  35134. function StandardMaterial(name, scene) {
  35135. var _this = _super.call(this, name, scene) || this;
  35136. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  35137. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  35138. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  35139. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35140. _this.specularPower = 64;
  35141. _this._useAlphaFromDiffuseTexture = false;
  35142. _this._useEmissiveAsIllumination = false;
  35143. _this._linkEmissiveWithDiffuse = false;
  35144. _this._useSpecularOverAlpha = false;
  35145. _this._useReflectionOverAlpha = false;
  35146. _this._disableLighting = false;
  35147. _this._useParallax = false;
  35148. _this._useParallaxOcclusion = false;
  35149. _this.parallaxScaleBias = 0.05;
  35150. _this._roughness = 0;
  35151. _this.indexOfRefraction = 0.98;
  35152. _this.invertRefractionY = true;
  35153. _this._useLightmapAsShadowmap = false;
  35154. _this._useReflectionFresnelFromSpecular = false;
  35155. _this._useGlossinessFromSpecularMapAlpha = false;
  35156. _this._maxSimultaneousLights = 4;
  35157. /**
  35158. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35159. */
  35160. _this._invertNormalMapX = false;
  35161. /**
  35162. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35163. */
  35164. _this._invertNormalMapY = false;
  35165. /**
  35166. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35167. */
  35168. _this._twoSidedLighting = false;
  35169. _this._renderTargets = new BABYLON.SmartArray(16);
  35170. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  35171. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35172. // Setup the default processing configuration to the scene.
  35173. _this._attachImageProcessingConfiguration(null);
  35174. _this.getRenderTargetTextures = function () {
  35175. _this._renderTargets.reset();
  35176. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35177. _this._renderTargets.push(_this._reflectionTexture);
  35178. }
  35179. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35180. _this._renderTargets.push(_this._refractionTexture);
  35181. }
  35182. return _this._renderTargets;
  35183. };
  35184. return _this;
  35185. }
  35186. ;
  35187. ;
  35188. ;
  35189. ;
  35190. ;
  35191. ;
  35192. ;
  35193. ;
  35194. ;
  35195. ;
  35196. ;
  35197. ;
  35198. ;
  35199. ;
  35200. ;
  35201. ;
  35202. ;
  35203. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  35204. /**
  35205. * Gets the image processing configuration used either in this material.
  35206. */
  35207. get: function () {
  35208. return this._imageProcessingConfiguration;
  35209. },
  35210. /**
  35211. * Sets the Default image processing configuration used either in the this material.
  35212. *
  35213. * If sets to null, the scene one is in use.
  35214. */
  35215. set: function (value) {
  35216. this._attachImageProcessingConfiguration(value);
  35217. // Ensure the effect will be rebuilt.
  35218. this._markAllSubMeshesAsTexturesDirty();
  35219. },
  35220. enumerable: true,
  35221. configurable: true
  35222. });
  35223. /**
  35224. * Attaches a new image processing configuration to the Standard Material.
  35225. * @param configuration
  35226. */
  35227. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35228. var _this = this;
  35229. if (configuration === this._imageProcessingConfiguration) {
  35230. return;
  35231. }
  35232. // Detaches observer.
  35233. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35234. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35235. }
  35236. // Pick the scene configuration if needed.
  35237. if (!configuration) {
  35238. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35239. }
  35240. else {
  35241. this._imageProcessingConfiguration = configuration;
  35242. }
  35243. // Attaches observer.
  35244. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35245. _this._markAllSubMeshesAsImageProcessingDirty();
  35246. });
  35247. };
  35248. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  35249. /**
  35250. * Gets wether the color curves effect is enabled.
  35251. */
  35252. get: function () {
  35253. return this.imageProcessingConfiguration.colorCurvesEnabled;
  35254. },
  35255. /**
  35256. * Sets wether the color curves effect is enabled.
  35257. */
  35258. set: function (value) {
  35259. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  35260. },
  35261. enumerable: true,
  35262. configurable: true
  35263. });
  35264. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  35265. /**
  35266. * Gets wether the color grading effect is enabled.
  35267. */
  35268. get: function () {
  35269. return this.imageProcessingConfiguration.colorGradingEnabled;
  35270. },
  35271. /**
  35272. * Gets wether the color grading effect is enabled.
  35273. */
  35274. set: function (value) {
  35275. this.imageProcessingConfiguration.colorGradingEnabled = value;
  35276. },
  35277. enumerable: true,
  35278. configurable: true
  35279. });
  35280. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  35281. /**
  35282. * Gets wether tonemapping is enabled or not.
  35283. */
  35284. get: function () {
  35285. return this._imageProcessingConfiguration.toneMappingEnabled;
  35286. },
  35287. /**
  35288. * Sets wether tonemapping is enabled or not
  35289. */
  35290. set: function (value) {
  35291. this._imageProcessingConfiguration.toneMappingEnabled = value;
  35292. },
  35293. enumerable: true,
  35294. configurable: true
  35295. });
  35296. ;
  35297. ;
  35298. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  35299. /**
  35300. * The camera exposure used on this material.
  35301. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35302. * This corresponds to a photographic exposure.
  35303. */
  35304. get: function () {
  35305. return this._imageProcessingConfiguration.exposure;
  35306. },
  35307. /**
  35308. * The camera exposure used on this material.
  35309. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35310. * This corresponds to a photographic exposure.
  35311. */
  35312. set: function (value) {
  35313. this._imageProcessingConfiguration.exposure = value;
  35314. },
  35315. enumerable: true,
  35316. configurable: true
  35317. });
  35318. ;
  35319. ;
  35320. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  35321. /**
  35322. * Gets The camera contrast used on this material.
  35323. */
  35324. get: function () {
  35325. return this._imageProcessingConfiguration.contrast;
  35326. },
  35327. /**
  35328. * Sets The camera contrast used on this material.
  35329. */
  35330. set: function (value) {
  35331. this._imageProcessingConfiguration.contrast = value;
  35332. },
  35333. enumerable: true,
  35334. configurable: true
  35335. });
  35336. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  35337. /**
  35338. * Gets the Color Grading 2D Lookup Texture.
  35339. */
  35340. get: function () {
  35341. return this._imageProcessingConfiguration.colorGradingTexture;
  35342. },
  35343. /**
  35344. * Sets the Color Grading 2D Lookup Texture.
  35345. */
  35346. set: function (value) {
  35347. this._imageProcessingConfiguration.colorGradingTexture = value;
  35348. },
  35349. enumerable: true,
  35350. configurable: true
  35351. });
  35352. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  35353. /**
  35354. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35355. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35356. * 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;
  35357. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35358. */
  35359. get: function () {
  35360. return this._imageProcessingConfiguration.colorCurves;
  35361. },
  35362. /**
  35363. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35364. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35365. * 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;
  35366. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35367. */
  35368. set: function (value) {
  35369. this._imageProcessingConfiguration.colorCurves = value;
  35370. },
  35371. enumerable: true,
  35372. configurable: true
  35373. });
  35374. StandardMaterial.prototype.getClassName = function () {
  35375. return "StandardMaterial";
  35376. };
  35377. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  35378. get: function () {
  35379. return this._useLogarithmicDepth;
  35380. },
  35381. set: function (value) {
  35382. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35383. this._markAllSubMeshesAsMiscDirty();
  35384. },
  35385. enumerable: true,
  35386. configurable: true
  35387. });
  35388. StandardMaterial.prototype.needAlphaBlending = function () {
  35389. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  35390. };
  35391. StandardMaterial.prototype.needAlphaTesting = function () {
  35392. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  35393. };
  35394. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  35395. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  35396. };
  35397. StandardMaterial.prototype.getAlphaTestTexture = function () {
  35398. return this._diffuseTexture;
  35399. };
  35400. /**
  35401. * Child classes can use it to update shaders
  35402. */
  35403. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35404. if (useInstances === void 0) { useInstances = false; }
  35405. if (subMesh.effect && this.isFrozen) {
  35406. if (this._wasPreviouslyReady && subMesh.effect) {
  35407. return true;
  35408. }
  35409. }
  35410. if (!subMesh._materialDefines) {
  35411. subMesh._materialDefines = new StandardMaterialDefines();
  35412. }
  35413. var scene = this.getScene();
  35414. var defines = subMesh._materialDefines;
  35415. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35416. if (defines._renderId === scene.getRenderId()) {
  35417. return true;
  35418. }
  35419. }
  35420. var engine = scene.getEngine();
  35421. // Lights
  35422. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35423. // Textures
  35424. if (defines._areTexturesDirty) {
  35425. defines._needUVs = false;
  35426. defines.MAINUV1 = false;
  35427. defines.MAINUV2 = false;
  35428. if (scene.texturesEnabled) {
  35429. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35430. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  35431. return false;
  35432. }
  35433. else {
  35434. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  35435. }
  35436. }
  35437. else {
  35438. defines.DIFFUSE = false;
  35439. }
  35440. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35441. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35442. return false;
  35443. }
  35444. else {
  35445. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35446. }
  35447. }
  35448. else {
  35449. defines.AMBIENT = false;
  35450. }
  35451. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35452. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35453. return false;
  35454. }
  35455. else {
  35456. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35457. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35458. }
  35459. }
  35460. else {
  35461. defines.OPACITY = false;
  35462. }
  35463. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35464. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  35465. return false;
  35466. }
  35467. else {
  35468. defines._needNormals = true;
  35469. defines.REFLECTION = true;
  35470. defines.ROUGHNESS = (this._roughness > 0);
  35471. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  35472. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  35473. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  35474. switch (this._reflectionTexture.coordinatesMode) {
  35475. case BABYLON.Texture.CUBIC_MODE:
  35476. case BABYLON.Texture.INVCUBIC_MODE:
  35477. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  35478. break;
  35479. case BABYLON.Texture.EXPLICIT_MODE:
  35480. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  35481. break;
  35482. case BABYLON.Texture.PLANAR_MODE:
  35483. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  35484. break;
  35485. case BABYLON.Texture.PROJECTION_MODE:
  35486. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  35487. break;
  35488. case BABYLON.Texture.SKYBOX_MODE:
  35489. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  35490. break;
  35491. case BABYLON.Texture.SPHERICAL_MODE:
  35492. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  35493. break;
  35494. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35495. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  35496. break;
  35497. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35498. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  35499. break;
  35500. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35501. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  35502. break;
  35503. }
  35504. }
  35505. }
  35506. else {
  35507. defines.REFLECTION = false;
  35508. }
  35509. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35510. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35511. return false;
  35512. }
  35513. else {
  35514. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35515. }
  35516. }
  35517. else {
  35518. defines.EMISSIVE = false;
  35519. }
  35520. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35521. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35522. return false;
  35523. }
  35524. else {
  35525. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35526. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35527. }
  35528. }
  35529. else {
  35530. defines.LIGHTMAP = false;
  35531. }
  35532. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35533. if (!this._specularTexture.isReadyOrNotBlocking()) {
  35534. return false;
  35535. }
  35536. else {
  35537. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  35538. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  35539. }
  35540. }
  35541. else {
  35542. defines.SPECULAR = false;
  35543. }
  35544. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  35545. // Bump texure can not be not blocking.
  35546. if (!this._bumpTexture.isReady()) {
  35547. return false;
  35548. }
  35549. else {
  35550. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35551. defines.PARALLAX = this._useParallax;
  35552. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  35553. }
  35554. }
  35555. else {
  35556. defines.BUMP = false;
  35557. }
  35558. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35559. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35560. return false;
  35561. }
  35562. else {
  35563. defines._needUVs = true;
  35564. defines.REFRACTION = true;
  35565. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35566. }
  35567. }
  35568. else {
  35569. defines.REFRACTION = false;
  35570. }
  35571. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  35572. }
  35573. else {
  35574. defines.DIFFUSE = false;
  35575. defines.AMBIENT = false;
  35576. defines.OPACITY = false;
  35577. defines.REFLECTION = false;
  35578. defines.EMISSIVE = false;
  35579. defines.LIGHTMAP = false;
  35580. defines.BUMP = false;
  35581. defines.REFRACTION = false;
  35582. }
  35583. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  35584. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  35585. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  35586. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35587. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35588. }
  35589. if (defines._areImageProcessingDirty) {
  35590. if (!this._imageProcessingConfiguration.isReady()) {
  35591. return false;
  35592. }
  35593. this._imageProcessingConfiguration.prepareDefines(defines);
  35594. }
  35595. if (defines._areFresnelDirty) {
  35596. if (StandardMaterial.FresnelEnabled) {
  35597. // Fresnel
  35598. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  35599. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  35600. this._reflectionFresnelParameters) {
  35601. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  35602. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  35603. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  35604. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  35605. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  35606. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  35607. defines._needNormals = true;
  35608. defines.FRESNEL = true;
  35609. }
  35610. }
  35611. else {
  35612. defines.FRESNEL = false;
  35613. }
  35614. }
  35615. // Misc.
  35616. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35617. // Attribs
  35618. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  35619. // Values that need to be evaluated on every frame
  35620. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._shouldTurnAlphaTestOn(mesh));
  35621. // Get correct effect
  35622. if (defines.isDirty) {
  35623. defines.markAsProcessed();
  35624. scene.resetCachedMaterial();
  35625. // Fallbacks
  35626. var fallbacks = new BABYLON.EffectFallbacks();
  35627. if (defines.REFLECTION) {
  35628. fallbacks.addFallback(0, "REFLECTION");
  35629. }
  35630. if (defines.SPECULAR) {
  35631. fallbacks.addFallback(0, "SPECULAR");
  35632. }
  35633. if (defines.BUMP) {
  35634. fallbacks.addFallback(0, "BUMP");
  35635. }
  35636. if (defines.PARALLAX) {
  35637. fallbacks.addFallback(1, "PARALLAX");
  35638. }
  35639. if (defines.PARALLAXOCCLUSION) {
  35640. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35641. }
  35642. if (defines.SPECULAROVERALPHA) {
  35643. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35644. }
  35645. if (defines.FOG) {
  35646. fallbacks.addFallback(1, "FOG");
  35647. }
  35648. if (defines.POINTSIZE) {
  35649. fallbacks.addFallback(0, "POINTSIZE");
  35650. }
  35651. if (defines.LOGARITHMICDEPTH) {
  35652. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35653. }
  35654. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35655. if (defines.SPECULARTERM) {
  35656. fallbacks.addFallback(0, "SPECULARTERM");
  35657. }
  35658. if (defines.DIFFUSEFRESNEL) {
  35659. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  35660. }
  35661. if (defines.OPACITYFRESNEL) {
  35662. fallbacks.addFallback(2, "OPACITYFRESNEL");
  35663. }
  35664. if (defines.REFLECTIONFRESNEL) {
  35665. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  35666. }
  35667. if (defines.EMISSIVEFRESNEL) {
  35668. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  35669. }
  35670. if (defines.FRESNEL) {
  35671. fallbacks.addFallback(4, "FRESNEL");
  35672. }
  35673. //Attributes
  35674. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35675. if (defines.NORMAL) {
  35676. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35677. }
  35678. if (defines.UV1) {
  35679. attribs.push(BABYLON.VertexBuffer.UVKind);
  35680. }
  35681. if (defines.UV2) {
  35682. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35683. }
  35684. if (defines.VERTEXCOLOR) {
  35685. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35686. }
  35687. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35688. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35689. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35690. var shaderName = "default";
  35691. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  35692. "vFogInfos", "vFogColor", "pointSize",
  35693. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35694. "mBones",
  35695. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35696. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  35697. "logarithmicDepthConstant", "vTangentSpaceParams"
  35698. ];
  35699. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35700. var uniformBuffers = ["Material", "Scene"];
  35701. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35702. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35703. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35704. uniformsNames: uniforms,
  35705. uniformBuffersNames: uniformBuffers,
  35706. samplers: samplers,
  35707. defines: defines,
  35708. maxSimultaneousLights: this._maxSimultaneousLights
  35709. });
  35710. if (this.customShaderNameResolve) {
  35711. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35712. }
  35713. var join = defines.toString();
  35714. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35715. attributes: attribs,
  35716. uniformsNames: uniforms,
  35717. uniformBuffersNames: uniformBuffers,
  35718. samplers: samplers,
  35719. defines: join,
  35720. fallbacks: fallbacks,
  35721. onCompiled: this.onCompiled,
  35722. onError: this.onError,
  35723. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35724. }, engine), defines);
  35725. this.buildUniformLayout();
  35726. }
  35727. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35728. return false;
  35729. }
  35730. defines._renderId = scene.getRenderId();
  35731. this._wasPreviouslyReady = true;
  35732. return true;
  35733. };
  35734. StandardMaterial.prototype.buildUniformLayout = function () {
  35735. // Order is important !
  35736. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35737. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35738. this._uniformBuffer.addUniform("opacityParts", 4);
  35739. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35740. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35741. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35742. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35743. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35744. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35745. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35746. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35747. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35748. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35749. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35750. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35751. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35752. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35753. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35754. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35755. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35756. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35757. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35758. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35759. this._uniformBuffer.addUniform("specularMatrix", 16);
  35760. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35761. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35762. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35763. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35764. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35765. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35766. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35767. this._uniformBuffer.addUniform("pointSize", 1);
  35768. this._uniformBuffer.create();
  35769. };
  35770. StandardMaterial.prototype.unbind = function () {
  35771. if (this._activeEffect) {
  35772. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35773. this._activeEffect.setTexture("reflection2DSampler", null);
  35774. }
  35775. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35776. this._activeEffect.setTexture("refraction2DSampler", null);
  35777. }
  35778. }
  35779. _super.prototype.unbind.call(this);
  35780. };
  35781. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35782. var scene = this.getScene();
  35783. var defines = subMesh._materialDefines;
  35784. if (!defines) {
  35785. return;
  35786. }
  35787. var effect = subMesh.effect;
  35788. if (!effect) {
  35789. return;
  35790. }
  35791. this._activeEffect = effect;
  35792. // Matrices
  35793. this.bindOnlyWorldMatrix(world);
  35794. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35795. // Bones
  35796. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35797. if (mustRebind) {
  35798. this._uniformBuffer.bindToEffect(effect, "Material");
  35799. this.bindViewProjection(effect);
  35800. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35801. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35802. // Fresnel
  35803. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35804. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35805. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35806. }
  35807. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35808. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35809. }
  35810. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35811. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35812. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35813. }
  35814. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35815. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35816. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35817. }
  35818. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35819. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35820. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35821. }
  35822. }
  35823. // Textures
  35824. if (scene.texturesEnabled) {
  35825. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35826. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35827. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  35828. }
  35829. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35830. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35831. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35832. }
  35833. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35834. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35835. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35836. }
  35837. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35838. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35839. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35840. }
  35841. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35842. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35843. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35844. }
  35845. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35846. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35847. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35848. }
  35849. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35850. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35851. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  35852. }
  35853. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35854. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35855. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35856. if (scene._mirroredCameraPosition) {
  35857. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35858. }
  35859. else {
  35860. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35861. }
  35862. }
  35863. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35864. var depth = 1.0;
  35865. if (!this._refractionTexture.isCube) {
  35866. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35867. if (this._refractionTexture.depth) {
  35868. depth = this._refractionTexture.depth;
  35869. }
  35870. }
  35871. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35872. }
  35873. }
  35874. // Point size
  35875. if (this.pointsCloud) {
  35876. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35877. }
  35878. if (defines.SPECULARTERM) {
  35879. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35880. }
  35881. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35882. // Diffuse
  35883. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35884. }
  35885. // Textures
  35886. if (scene.texturesEnabled) {
  35887. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35888. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35889. }
  35890. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35891. effect.setTexture("ambientSampler", this._ambientTexture);
  35892. }
  35893. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35894. effect.setTexture("opacitySampler", this._opacityTexture);
  35895. }
  35896. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35897. if (this._reflectionTexture.isCube) {
  35898. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35899. }
  35900. else {
  35901. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35902. }
  35903. }
  35904. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35905. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35906. }
  35907. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35908. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35909. }
  35910. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35911. effect.setTexture("specularSampler", this._specularTexture);
  35912. }
  35913. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35914. effect.setTexture("bumpSampler", this._bumpTexture);
  35915. }
  35916. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35917. var depth = 1.0;
  35918. if (this._refractionTexture.isCube) {
  35919. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35920. }
  35921. else {
  35922. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35923. }
  35924. }
  35925. }
  35926. // Clip plane
  35927. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35928. // Colors
  35929. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35930. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  35931. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35932. }
  35933. if (mustRebind || !this.isFrozen) {
  35934. // Lights
  35935. if (scene.lightsEnabled && !this._disableLighting) {
  35936. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35937. }
  35938. // View
  35939. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35940. this.bindView(effect);
  35941. }
  35942. // Fog
  35943. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35944. // Morph targets
  35945. if (defines.NUM_MORPH_INFLUENCERS) {
  35946. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35947. }
  35948. // Log. depth
  35949. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35950. // image processing
  35951. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  35952. this._imageProcessingConfiguration.bind(this._activeEffect);
  35953. }
  35954. }
  35955. this._uniformBuffer.update();
  35956. this._afterBind(mesh, this._activeEffect);
  35957. };
  35958. StandardMaterial.prototype.getAnimatables = function () {
  35959. var results = [];
  35960. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35961. results.push(this._diffuseTexture);
  35962. }
  35963. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35964. results.push(this._ambientTexture);
  35965. }
  35966. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35967. results.push(this._opacityTexture);
  35968. }
  35969. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35970. results.push(this._reflectionTexture);
  35971. }
  35972. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35973. results.push(this._emissiveTexture);
  35974. }
  35975. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35976. results.push(this._specularTexture);
  35977. }
  35978. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35979. results.push(this._bumpTexture);
  35980. }
  35981. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35982. results.push(this._lightmapTexture);
  35983. }
  35984. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35985. results.push(this._refractionTexture);
  35986. }
  35987. return results;
  35988. };
  35989. StandardMaterial.prototype.getActiveTextures = function () {
  35990. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35991. if (this._diffuseTexture) {
  35992. activeTextures.push(this._diffuseTexture);
  35993. }
  35994. if (this._ambientTexture) {
  35995. activeTextures.push(this._ambientTexture);
  35996. }
  35997. if (this._opacityTexture) {
  35998. activeTextures.push(this._opacityTexture);
  35999. }
  36000. if (this._reflectionTexture) {
  36001. activeTextures.push(this._reflectionTexture);
  36002. }
  36003. if (this._emissiveTexture) {
  36004. activeTextures.push(this._emissiveTexture);
  36005. }
  36006. if (this._specularTexture) {
  36007. activeTextures.push(this._specularTexture);
  36008. }
  36009. if (this._bumpTexture) {
  36010. activeTextures.push(this._bumpTexture);
  36011. }
  36012. if (this._lightmapTexture) {
  36013. activeTextures.push(this._lightmapTexture);
  36014. }
  36015. if (this._refractionTexture) {
  36016. activeTextures.push(this._refractionTexture);
  36017. }
  36018. return activeTextures;
  36019. };
  36020. StandardMaterial.prototype.hasTexture = function (texture) {
  36021. if (_super.prototype.hasTexture.call(this, texture)) {
  36022. return true;
  36023. }
  36024. if (this._diffuseTexture === texture) {
  36025. return true;
  36026. }
  36027. if (this._ambientTexture === texture) {
  36028. return true;
  36029. }
  36030. if (this._opacityTexture === texture) {
  36031. return true;
  36032. }
  36033. if (this._reflectionTexture === texture) {
  36034. return true;
  36035. }
  36036. if (this._emissiveTexture === texture) {
  36037. return true;
  36038. }
  36039. if (this._specularTexture === texture) {
  36040. return true;
  36041. }
  36042. if (this._bumpTexture === texture) {
  36043. return true;
  36044. }
  36045. if (this._lightmapTexture === texture) {
  36046. return true;
  36047. }
  36048. if (this._refractionTexture === texture) {
  36049. return true;
  36050. }
  36051. return false;
  36052. };
  36053. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36054. if (forceDisposeTextures) {
  36055. if (this._diffuseTexture) {
  36056. this._diffuseTexture.dispose();
  36057. }
  36058. if (this._ambientTexture) {
  36059. this._ambientTexture.dispose();
  36060. }
  36061. if (this._opacityTexture) {
  36062. this._opacityTexture.dispose();
  36063. }
  36064. if (this._reflectionTexture) {
  36065. this._reflectionTexture.dispose();
  36066. }
  36067. if (this._emissiveTexture) {
  36068. this._emissiveTexture.dispose();
  36069. }
  36070. if (this._specularTexture) {
  36071. this._specularTexture.dispose();
  36072. }
  36073. if (this._bumpTexture) {
  36074. this._bumpTexture.dispose();
  36075. }
  36076. if (this._lightmapTexture) {
  36077. this._lightmapTexture.dispose();
  36078. }
  36079. if (this._refractionTexture) {
  36080. this._refractionTexture.dispose();
  36081. }
  36082. }
  36083. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36084. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36085. }
  36086. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36087. };
  36088. StandardMaterial.prototype.clone = function (name) {
  36089. var _this = this;
  36090. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  36091. result.name = name;
  36092. result.id = name;
  36093. return result;
  36094. };
  36095. StandardMaterial.prototype.serialize = function () {
  36096. return BABYLON.SerializationHelper.Serialize(this);
  36097. };
  36098. // Statics
  36099. StandardMaterial.Parse = function (source, scene, rootUrl) {
  36100. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  36101. };
  36102. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  36103. get: function () {
  36104. return StandardMaterial._DiffuseTextureEnabled;
  36105. },
  36106. set: function (value) {
  36107. if (StandardMaterial._DiffuseTextureEnabled === value) {
  36108. return;
  36109. }
  36110. StandardMaterial._DiffuseTextureEnabled = value;
  36111. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36112. },
  36113. enumerable: true,
  36114. configurable: true
  36115. });
  36116. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  36117. get: function () {
  36118. return StandardMaterial._AmbientTextureEnabled;
  36119. },
  36120. set: function (value) {
  36121. if (StandardMaterial._AmbientTextureEnabled === value) {
  36122. return;
  36123. }
  36124. StandardMaterial._AmbientTextureEnabled = value;
  36125. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36126. },
  36127. enumerable: true,
  36128. configurable: true
  36129. });
  36130. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  36131. get: function () {
  36132. return StandardMaterial._OpacityTextureEnabled;
  36133. },
  36134. set: function (value) {
  36135. if (StandardMaterial._OpacityTextureEnabled === value) {
  36136. return;
  36137. }
  36138. StandardMaterial._OpacityTextureEnabled = value;
  36139. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36140. },
  36141. enumerable: true,
  36142. configurable: true
  36143. });
  36144. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  36145. get: function () {
  36146. return StandardMaterial._ReflectionTextureEnabled;
  36147. },
  36148. set: function (value) {
  36149. if (StandardMaterial._ReflectionTextureEnabled === value) {
  36150. return;
  36151. }
  36152. StandardMaterial._ReflectionTextureEnabled = value;
  36153. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36154. },
  36155. enumerable: true,
  36156. configurable: true
  36157. });
  36158. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  36159. get: function () {
  36160. return StandardMaterial._EmissiveTextureEnabled;
  36161. },
  36162. set: function (value) {
  36163. if (StandardMaterial._EmissiveTextureEnabled === value) {
  36164. return;
  36165. }
  36166. StandardMaterial._EmissiveTextureEnabled = value;
  36167. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36168. },
  36169. enumerable: true,
  36170. configurable: true
  36171. });
  36172. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  36173. get: function () {
  36174. return StandardMaterial._SpecularTextureEnabled;
  36175. },
  36176. set: function (value) {
  36177. if (StandardMaterial._SpecularTextureEnabled === value) {
  36178. return;
  36179. }
  36180. StandardMaterial._SpecularTextureEnabled = value;
  36181. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36182. },
  36183. enumerable: true,
  36184. configurable: true
  36185. });
  36186. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  36187. get: function () {
  36188. return StandardMaterial._BumpTextureEnabled;
  36189. },
  36190. set: function (value) {
  36191. if (StandardMaterial._BumpTextureEnabled === value) {
  36192. return;
  36193. }
  36194. StandardMaterial._BumpTextureEnabled = value;
  36195. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36196. },
  36197. enumerable: true,
  36198. configurable: true
  36199. });
  36200. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  36201. get: function () {
  36202. return StandardMaterial._LightmapTextureEnabled;
  36203. },
  36204. set: function (value) {
  36205. if (StandardMaterial._LightmapTextureEnabled === value) {
  36206. return;
  36207. }
  36208. StandardMaterial._LightmapTextureEnabled = value;
  36209. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36210. },
  36211. enumerable: true,
  36212. configurable: true
  36213. });
  36214. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  36215. get: function () {
  36216. return StandardMaterial._RefractionTextureEnabled;
  36217. },
  36218. set: function (value) {
  36219. if (StandardMaterial._RefractionTextureEnabled === value) {
  36220. return;
  36221. }
  36222. StandardMaterial._RefractionTextureEnabled = value;
  36223. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36224. },
  36225. enumerable: true,
  36226. configurable: true
  36227. });
  36228. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  36229. get: function () {
  36230. return StandardMaterial._ColorGradingTextureEnabled;
  36231. },
  36232. set: function (value) {
  36233. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  36234. return;
  36235. }
  36236. StandardMaterial._ColorGradingTextureEnabled = value;
  36237. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36238. },
  36239. enumerable: true,
  36240. configurable: true
  36241. });
  36242. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  36243. get: function () {
  36244. return StandardMaterial._FresnelEnabled;
  36245. },
  36246. set: function (value) {
  36247. if (StandardMaterial._FresnelEnabled === value) {
  36248. return;
  36249. }
  36250. StandardMaterial._FresnelEnabled = value;
  36251. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  36252. },
  36253. enumerable: true,
  36254. configurable: true
  36255. });
  36256. // Flags used to enable or disable a type of texture for all Standard Materials
  36257. StandardMaterial._DiffuseTextureEnabled = true;
  36258. StandardMaterial._AmbientTextureEnabled = true;
  36259. StandardMaterial._OpacityTextureEnabled = true;
  36260. StandardMaterial._ReflectionTextureEnabled = true;
  36261. StandardMaterial._EmissiveTextureEnabled = true;
  36262. StandardMaterial._SpecularTextureEnabled = true;
  36263. StandardMaterial._BumpTextureEnabled = true;
  36264. StandardMaterial._LightmapTextureEnabled = true;
  36265. StandardMaterial._RefractionTextureEnabled = true;
  36266. StandardMaterial._ColorGradingTextureEnabled = true;
  36267. StandardMaterial._FresnelEnabled = true;
  36268. __decorate([
  36269. BABYLON.serializeAsTexture("diffuseTexture")
  36270. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  36271. __decorate([
  36272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36273. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  36274. __decorate([
  36275. BABYLON.serializeAsTexture("ambientTexture")
  36276. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  36277. __decorate([
  36278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36279. ], StandardMaterial.prototype, "ambientTexture", void 0);
  36280. __decorate([
  36281. BABYLON.serializeAsTexture("opacityTexture")
  36282. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  36283. __decorate([
  36284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36285. ], StandardMaterial.prototype, "opacityTexture", void 0);
  36286. __decorate([
  36287. BABYLON.serializeAsTexture("reflectionTexture")
  36288. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  36289. __decorate([
  36290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36291. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  36292. __decorate([
  36293. BABYLON.serializeAsTexture("emissiveTexture")
  36294. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  36295. __decorate([
  36296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36297. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  36298. __decorate([
  36299. BABYLON.serializeAsTexture("specularTexture")
  36300. ], StandardMaterial.prototype, "_specularTexture", void 0);
  36301. __decorate([
  36302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36303. ], StandardMaterial.prototype, "specularTexture", void 0);
  36304. __decorate([
  36305. BABYLON.serializeAsTexture("bumpTexture")
  36306. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  36307. __decorate([
  36308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36309. ], StandardMaterial.prototype, "bumpTexture", void 0);
  36310. __decorate([
  36311. BABYLON.serializeAsTexture("lightmapTexture")
  36312. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  36313. __decorate([
  36314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36315. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  36316. __decorate([
  36317. BABYLON.serializeAsTexture("refractionTexture")
  36318. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  36319. __decorate([
  36320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36321. ], StandardMaterial.prototype, "refractionTexture", void 0);
  36322. __decorate([
  36323. BABYLON.serializeAsColor3("ambient")
  36324. ], StandardMaterial.prototype, "ambientColor", void 0);
  36325. __decorate([
  36326. BABYLON.serializeAsColor3("diffuse")
  36327. ], StandardMaterial.prototype, "diffuseColor", void 0);
  36328. __decorate([
  36329. BABYLON.serializeAsColor3("specular")
  36330. ], StandardMaterial.prototype, "specularColor", void 0);
  36331. __decorate([
  36332. BABYLON.serializeAsColor3("emissive")
  36333. ], StandardMaterial.prototype, "emissiveColor", void 0);
  36334. __decorate([
  36335. BABYLON.serialize()
  36336. ], StandardMaterial.prototype, "specularPower", void 0);
  36337. __decorate([
  36338. BABYLON.serialize("useAlphaFromDiffuseTexture")
  36339. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  36340. __decorate([
  36341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36342. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  36343. __decorate([
  36344. BABYLON.serialize("useEmissiveAsIllumination")
  36345. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  36346. __decorate([
  36347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36348. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  36349. __decorate([
  36350. BABYLON.serialize("linkEmissiveWithDiffuse")
  36351. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  36352. __decorate([
  36353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36354. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  36355. __decorate([
  36356. BABYLON.serialize("useSpecularOverAlpha")
  36357. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  36358. __decorate([
  36359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36360. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  36361. __decorate([
  36362. BABYLON.serialize("useReflectionOverAlpha")
  36363. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  36364. __decorate([
  36365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36366. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  36367. __decorate([
  36368. BABYLON.serialize("disableLighting")
  36369. ], StandardMaterial.prototype, "_disableLighting", void 0);
  36370. __decorate([
  36371. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36372. ], StandardMaterial.prototype, "disableLighting", void 0);
  36373. __decorate([
  36374. BABYLON.serialize("useParallax")
  36375. ], StandardMaterial.prototype, "_useParallax", void 0);
  36376. __decorate([
  36377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36378. ], StandardMaterial.prototype, "useParallax", void 0);
  36379. __decorate([
  36380. BABYLON.serialize("useParallaxOcclusion")
  36381. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  36382. __decorate([
  36383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36384. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  36385. __decorate([
  36386. BABYLON.serialize()
  36387. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  36388. __decorate([
  36389. BABYLON.serialize("roughness")
  36390. ], StandardMaterial.prototype, "_roughness", void 0);
  36391. __decorate([
  36392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36393. ], StandardMaterial.prototype, "roughness", void 0);
  36394. __decorate([
  36395. BABYLON.serialize()
  36396. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  36397. __decorate([
  36398. BABYLON.serialize()
  36399. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  36400. __decorate([
  36401. BABYLON.serialize("useLightmapAsShadowmap")
  36402. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  36403. __decorate([
  36404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36405. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36406. __decorate([
  36407. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  36408. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  36409. __decorate([
  36410. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36411. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  36412. __decorate([
  36413. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  36414. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  36415. __decorate([
  36416. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36417. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  36418. __decorate([
  36419. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  36420. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  36421. __decorate([
  36422. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36423. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  36424. __decorate([
  36425. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  36426. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  36427. __decorate([
  36428. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36429. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  36430. __decorate([
  36431. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  36432. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  36433. __decorate([
  36434. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36435. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  36436. __decorate([
  36437. BABYLON.serialize("useReflectionFresnelFromSpecular")
  36438. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  36439. __decorate([
  36440. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36441. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  36442. __decorate([
  36443. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  36444. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  36445. __decorate([
  36446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36447. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  36448. __decorate([
  36449. BABYLON.serialize("maxSimultaneousLights")
  36450. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  36451. __decorate([
  36452. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36453. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  36454. __decorate([
  36455. BABYLON.serialize("invertNormalMapX")
  36456. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  36457. __decorate([
  36458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36459. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  36460. __decorate([
  36461. BABYLON.serialize("invertNormalMapY")
  36462. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  36463. __decorate([
  36464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36465. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  36466. __decorate([
  36467. BABYLON.serialize("twoSidedLighting")
  36468. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  36469. __decorate([
  36470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36471. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  36472. __decorate([
  36473. BABYLON.serialize()
  36474. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  36475. return StandardMaterial;
  36476. }(BABYLON.PushMaterial));
  36477. BABYLON.StandardMaterial = StandardMaterial;
  36478. })(BABYLON || (BABYLON = {}));
  36479. //# sourceMappingURL=babylon.standardMaterial.js.map
  36480. var BABYLON;
  36481. (function (BABYLON) {
  36482. var PBRMaterialDefines = /** @class */ (function (_super) {
  36483. __extends(PBRMaterialDefines, _super);
  36484. function PBRMaterialDefines() {
  36485. var _this = _super.call(this) || this;
  36486. _this.PBR = true;
  36487. _this.MAINUV1 = false;
  36488. _this.MAINUV2 = false;
  36489. _this.UV1 = false;
  36490. _this.UV2 = false;
  36491. _this.ALBEDO = false;
  36492. _this.ALBEDODIRECTUV = 0;
  36493. _this.VERTEXCOLOR = false;
  36494. _this.AMBIENT = false;
  36495. _this.AMBIENTDIRECTUV = 0;
  36496. _this.AMBIENTINGRAYSCALE = false;
  36497. _this.OPACITY = false;
  36498. _this.VERTEXALPHA = false;
  36499. _this.OPACITYDIRECTUV = 0;
  36500. _this.OPACITYRGB = false;
  36501. _this.ALPHATEST = false;
  36502. _this.DEPTHPREPASS = false;
  36503. _this.ALPHABLEND = false;
  36504. _this.ALPHAFROMALBEDO = false;
  36505. _this.ALPHATESTVALUE = 0.5;
  36506. _this.SPECULAROVERALPHA = false;
  36507. _this.RADIANCEOVERALPHA = false;
  36508. _this.ALPHAFRESNEL = false;
  36509. _this.LINEARALPHAFRESNEL = false;
  36510. _this.PREMULTIPLYALPHA = false;
  36511. _this.EMISSIVE = false;
  36512. _this.EMISSIVEDIRECTUV = 0;
  36513. _this.REFLECTIVITY = false;
  36514. _this.REFLECTIVITYDIRECTUV = 0;
  36515. _this.SPECULARTERM = false;
  36516. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  36517. _this.MICROSURFACEAUTOMATIC = false;
  36518. _this.LODBASEDMICROSFURACE = false;
  36519. _this.MICROSURFACEMAP = false;
  36520. _this.MICROSURFACEMAPDIRECTUV = 0;
  36521. _this.METALLICWORKFLOW = false;
  36522. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  36523. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  36524. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  36525. _this.AOSTOREINMETALMAPRED = false;
  36526. _this.ENVIRONMENTBRDF = false;
  36527. _this.NORMAL = false;
  36528. _this.TANGENT = false;
  36529. _this.BUMP = false;
  36530. _this.BUMPDIRECTUV = 0;
  36531. _this.PARALLAX = false;
  36532. _this.PARALLAXOCCLUSION = false;
  36533. _this.NORMALXYSCALE = true;
  36534. _this.LIGHTMAP = false;
  36535. _this.LIGHTMAPDIRECTUV = 0;
  36536. _this.USELIGHTMAPASSHADOWMAP = false;
  36537. _this.REFLECTION = false;
  36538. _this.REFLECTIONMAP_3D = false;
  36539. _this.REFLECTIONMAP_SPHERICAL = false;
  36540. _this.REFLECTIONMAP_PLANAR = false;
  36541. _this.REFLECTIONMAP_CUBIC = false;
  36542. _this.REFLECTIONMAP_PROJECTION = false;
  36543. _this.REFLECTIONMAP_SKYBOX = false;
  36544. _this.REFLECTIONMAP_EXPLICIT = false;
  36545. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36546. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36547. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36548. _this.INVERTCUBICMAP = false;
  36549. _this.USESPHERICALFROMREFLECTIONMAP = false;
  36550. _this.USESPHERICALINVERTEX = false;
  36551. _this.REFLECTIONMAP_OPPOSITEZ = false;
  36552. _this.LODINREFLECTIONALPHA = false;
  36553. _this.GAMMAREFLECTION = false;
  36554. _this.RADIANCEOCCLUSION = false;
  36555. _this.HORIZONOCCLUSION = false;
  36556. _this.REFRACTION = false;
  36557. _this.REFRACTIONMAP_3D = false;
  36558. _this.REFRACTIONMAP_OPPOSITEZ = false;
  36559. _this.LODINREFRACTIONALPHA = false;
  36560. _this.GAMMAREFRACTION = false;
  36561. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  36562. _this.INSTANCES = false;
  36563. _this.NUM_BONE_INFLUENCERS = 0;
  36564. _this.BonesPerMesh = 0;
  36565. _this.NONUNIFORMSCALING = false;
  36566. _this.MORPHTARGETS = false;
  36567. _this.MORPHTARGETS_NORMAL = false;
  36568. _this.MORPHTARGETS_TANGENT = false;
  36569. _this.NUM_MORPH_INFLUENCERS = 0;
  36570. _this.IMAGEPROCESSING = false;
  36571. _this.VIGNETTE = false;
  36572. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36573. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36574. _this.TONEMAPPING = false;
  36575. _this.CONTRAST = false;
  36576. _this.COLORCURVES = false;
  36577. _this.COLORGRADING = false;
  36578. _this.COLORGRADING3D = false;
  36579. _this.SAMPLER3DGREENDEPTH = false;
  36580. _this.SAMPLER3DBGRMAP = false;
  36581. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36582. _this.EXPOSURE = false;
  36583. _this.USEPHYSICALLIGHTFALLOFF = false;
  36584. _this.TWOSIDEDLIGHTING = false;
  36585. _this.SHADOWFLOAT = false;
  36586. _this.CLIPPLANE = false;
  36587. _this.POINTSIZE = false;
  36588. _this.FOG = false;
  36589. _this.LOGARITHMICDEPTH = false;
  36590. _this.FORCENORMALFORWARD = false;
  36591. _this.rebuild();
  36592. return _this;
  36593. }
  36594. PBRMaterialDefines.prototype.reset = function () {
  36595. _super.prototype.reset.call(this);
  36596. this.ALPHATESTVALUE = 0.5;
  36597. this.PBR = true;
  36598. };
  36599. return PBRMaterialDefines;
  36600. }(BABYLON.MaterialDefines));
  36601. /**
  36602. * The Physically based material base class of BJS.
  36603. *
  36604. * This offers the main features of a standard PBR material.
  36605. * For more information, please refer to the documentation :
  36606. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36607. */
  36608. var PBRBaseMaterial = /** @class */ (function (_super) {
  36609. __extends(PBRBaseMaterial, _super);
  36610. /**
  36611. * Instantiates a new PBRMaterial instance.
  36612. *
  36613. * @param name The material name
  36614. * @param scene The scene the material will be use in.
  36615. */
  36616. function PBRBaseMaterial(name, scene) {
  36617. var _this = _super.call(this, name, scene) || this;
  36618. /**
  36619. * Intensity of the direct lights e.g. the four lights available in your scene.
  36620. * This impacts both the direct diffuse and specular highlights.
  36621. */
  36622. _this._directIntensity = 1.0;
  36623. /**
  36624. * Intensity of the emissive part of the material.
  36625. * This helps controlling the emissive effect without modifying the emissive color.
  36626. */
  36627. _this._emissiveIntensity = 1.0;
  36628. /**
  36629. * Intensity of the environment e.g. how much the environment will light the object
  36630. * either through harmonics for rough material or through the refelction for shiny ones.
  36631. */
  36632. _this._environmentIntensity = 1.0;
  36633. /**
  36634. * This is a special control allowing the reduction of the specular highlights coming from the
  36635. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36636. */
  36637. _this._specularIntensity = 1.0;
  36638. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  36639. /**
  36640. * Debug Control allowing disabling the bump map on this material.
  36641. */
  36642. _this._disableBumpMap = false;
  36643. /**
  36644. * AKA Occlusion Texture Intensity in other nomenclature.
  36645. */
  36646. _this._ambientTextureStrength = 1.0;
  36647. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  36648. /**
  36649. * AKA Diffuse Color in other nomenclature.
  36650. */
  36651. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  36652. /**
  36653. * AKA Specular Color in other nomenclature.
  36654. */
  36655. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36656. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  36657. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  36658. /**
  36659. * AKA Glossiness in other nomenclature.
  36660. */
  36661. _this._microSurface = 0.9;
  36662. /**
  36663. * source material index of refraction (IOR)' / 'destination material IOR.
  36664. */
  36665. _this._indexOfRefraction = 0.66;
  36666. /**
  36667. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36668. */
  36669. _this._invertRefractionY = false;
  36670. /**
  36671. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36672. * Materials half opaque for instance using refraction could benefit from this control.
  36673. */
  36674. _this._linkRefractionWithTransparency = false;
  36675. _this._useLightmapAsShadowmap = false;
  36676. /**
  36677. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  36678. * makes the reflect vector face the model (under horizon).
  36679. */
  36680. _this._useHorizonOcclusion = true;
  36681. /**
  36682. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  36683. * too much the area relying on ambient texture to define their ambient occlusion.
  36684. */
  36685. _this._useRadianceOcclusion = true;
  36686. /**
  36687. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36688. */
  36689. _this._useAlphaFromAlbedoTexture = false;
  36690. /**
  36691. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36692. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36693. */
  36694. _this._useSpecularOverAlpha = true;
  36695. /**
  36696. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36697. */
  36698. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  36699. /**
  36700. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36701. */
  36702. _this._useRoughnessFromMetallicTextureAlpha = true;
  36703. /**
  36704. * Specifies if the metallic texture contains the roughness information in its green channel.
  36705. */
  36706. _this._useRoughnessFromMetallicTextureGreen = false;
  36707. /**
  36708. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36709. */
  36710. _this._useMetallnessFromMetallicTextureBlue = false;
  36711. /**
  36712. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36713. */
  36714. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  36715. /**
  36716. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36717. */
  36718. _this._useAmbientInGrayScale = false;
  36719. /**
  36720. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36721. * The material will try to infer what glossiness each pixel should be.
  36722. */
  36723. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  36724. /**
  36725. * BJS is using an harcoded light falloff based on a manually sets up range.
  36726. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36727. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36728. */
  36729. _this._usePhysicalLightFalloff = true;
  36730. /**
  36731. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36732. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36733. */
  36734. _this._useRadianceOverAlpha = true;
  36735. /**
  36736. * Allows using the bump map in parallax mode.
  36737. */
  36738. _this._useParallax = false;
  36739. /**
  36740. * Allows using the bump map in parallax occlusion mode.
  36741. */
  36742. _this._useParallaxOcclusion = false;
  36743. /**
  36744. * Controls the scale bias of the parallax mode.
  36745. */
  36746. _this._parallaxScaleBias = 0.05;
  36747. /**
  36748. * If sets to true, disables all the lights affecting the material.
  36749. */
  36750. _this._disableLighting = false;
  36751. /**
  36752. * Number of Simultaneous lights allowed on the material.
  36753. */
  36754. _this._maxSimultaneousLights = 4;
  36755. /**
  36756. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  36757. */
  36758. _this._invertNormalMapX = false;
  36759. /**
  36760. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  36761. */
  36762. _this._invertNormalMapY = false;
  36763. /**
  36764. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36765. */
  36766. _this._twoSidedLighting = false;
  36767. /**
  36768. * Defines the alpha limits in alpha test mode.
  36769. */
  36770. _this._alphaCutOff = 0.4;
  36771. /**
  36772. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36773. */
  36774. _this._forceAlphaTest = false;
  36775. /**
  36776. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36777. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  36778. */
  36779. _this._useAlphaFresnel = false;
  36780. /**
  36781. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36782. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  36783. */
  36784. _this._useLinearAlphaFresnel = false;
  36785. /**
  36786. * The transparency mode of the material.
  36787. */
  36788. _this._transparencyMode = null;
  36789. /**
  36790. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  36791. * from cos thetav and roughness:
  36792. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  36793. */
  36794. _this._environmentBRDFTexture = null;
  36795. /**
  36796. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36797. */
  36798. _this._forceIrradianceInFragment = false;
  36799. /**
  36800. * Force normal to face away from face.
  36801. */
  36802. _this._forceNormalForward = false;
  36803. /**
  36804. * Force metallic workflow.
  36805. */
  36806. _this._forceMetallicWorkflow = false;
  36807. _this._renderTargets = new BABYLON.SmartArray(16);
  36808. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36809. // Setup the default processing configuration to the scene.
  36810. _this._attachImageProcessingConfiguration(null);
  36811. _this.getRenderTargetTextures = function () {
  36812. _this._renderTargets.reset();
  36813. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36814. _this._renderTargets.push(_this._reflectionTexture);
  36815. }
  36816. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36817. _this._renderTargets.push(_this._refractionTexture);
  36818. }
  36819. return _this._renderTargets;
  36820. };
  36821. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36822. return _this;
  36823. }
  36824. /**
  36825. * Attaches a new image processing configuration to the PBR Material.
  36826. * @param configuration
  36827. */
  36828. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36829. var _this = this;
  36830. if (configuration === this._imageProcessingConfiguration) {
  36831. return;
  36832. }
  36833. // Detaches observer.
  36834. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36835. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36836. }
  36837. // Pick the scene configuration if needed.
  36838. if (!configuration) {
  36839. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36840. }
  36841. else {
  36842. this._imageProcessingConfiguration = configuration;
  36843. }
  36844. // Attaches observer.
  36845. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36846. _this._markAllSubMeshesAsImageProcessingDirty();
  36847. });
  36848. };
  36849. PBRBaseMaterial.prototype.getClassName = function () {
  36850. return "PBRBaseMaterial";
  36851. };
  36852. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  36853. get: function () {
  36854. return this._useLogarithmicDepth;
  36855. },
  36856. set: function (value) {
  36857. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36858. },
  36859. enumerable: true,
  36860. configurable: true
  36861. });
  36862. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  36863. /**
  36864. * Gets the current transparency mode.
  36865. */
  36866. get: function () {
  36867. return this._transparencyMode;
  36868. },
  36869. /**
  36870. * Sets the transparency mode of the material.
  36871. */
  36872. set: function (value) {
  36873. if (this._transparencyMode === value) {
  36874. return;
  36875. }
  36876. this._transparencyMode = value;
  36877. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  36878. this._markAllSubMeshesAsTexturesDirty();
  36879. },
  36880. enumerable: true,
  36881. configurable: true
  36882. });
  36883. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  36884. /**
  36885. * Returns true if alpha blending should be disabled.
  36886. */
  36887. get: function () {
  36888. return (this._linkRefractionWithTransparency ||
  36889. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  36890. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36891. },
  36892. enumerable: true,
  36893. configurable: true
  36894. });
  36895. /**
  36896. * Specifies whether or not this material should be rendered in alpha blend mode.
  36897. */
  36898. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  36899. if (this._disableAlphaBlending) {
  36900. return false;
  36901. }
  36902. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  36903. };
  36904. /**
  36905. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  36906. */
  36907. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  36908. if (this._disableAlphaBlending) {
  36909. return false;
  36910. }
  36911. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  36912. };
  36913. /**
  36914. * Specifies whether or not this material should be rendered in alpha test mode.
  36915. */
  36916. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  36917. if (this._forceAlphaTest) {
  36918. return true;
  36919. }
  36920. if (this._linkRefractionWithTransparency) {
  36921. return false;
  36922. }
  36923. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36924. };
  36925. /**
  36926. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  36927. */
  36928. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  36929. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36930. };
  36931. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  36932. return this._albedoTexture;
  36933. };
  36934. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36935. var _this = this;
  36936. if (subMesh.effect && this.isFrozen) {
  36937. if (this._wasPreviouslyReady) {
  36938. return true;
  36939. }
  36940. }
  36941. if (!subMesh._materialDefines) {
  36942. subMesh._materialDefines = new PBRMaterialDefines();
  36943. }
  36944. var scene = this.getScene();
  36945. var defines = subMesh._materialDefines;
  36946. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36947. if (defines._renderId === scene.getRenderId()) {
  36948. return true;
  36949. }
  36950. }
  36951. var engine = scene.getEngine();
  36952. // Lights
  36953. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36954. defines._needNormals = true;
  36955. // Textures
  36956. if (defines._areTexturesDirty) {
  36957. defines._needUVs = false;
  36958. if (scene.texturesEnabled) {
  36959. if (scene.getEngine().getCaps().textureLOD) {
  36960. defines.LODBASEDMICROSFURACE = true;
  36961. }
  36962. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36963. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  36964. return false;
  36965. }
  36966. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  36967. }
  36968. else {
  36969. defines.ALBEDO = false;
  36970. }
  36971. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36972. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36973. return false;
  36974. }
  36975. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36976. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  36977. }
  36978. else {
  36979. defines.AMBIENT = false;
  36980. }
  36981. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36982. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36983. return false;
  36984. }
  36985. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36986. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36987. }
  36988. else {
  36989. defines.OPACITY = false;
  36990. }
  36991. var reflectionTexture = this._getReflectionTexture();
  36992. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36993. if (!reflectionTexture.isReadyOrNotBlocking()) {
  36994. return false;
  36995. }
  36996. defines.REFLECTION = true;
  36997. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  36998. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  36999. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  37000. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  37001. defines.INVERTCUBICMAP = true;
  37002. }
  37003. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  37004. switch (reflectionTexture.coordinatesMode) {
  37005. case BABYLON.Texture.CUBIC_MODE:
  37006. case BABYLON.Texture.INVCUBIC_MODE:
  37007. defines.REFLECTIONMAP_CUBIC = true;
  37008. break;
  37009. case BABYLON.Texture.EXPLICIT_MODE:
  37010. defines.REFLECTIONMAP_EXPLICIT = true;
  37011. break;
  37012. case BABYLON.Texture.PLANAR_MODE:
  37013. defines.REFLECTIONMAP_PLANAR = true;
  37014. break;
  37015. case BABYLON.Texture.PROJECTION_MODE:
  37016. defines.REFLECTIONMAP_PROJECTION = true;
  37017. break;
  37018. case BABYLON.Texture.SKYBOX_MODE:
  37019. defines.REFLECTIONMAP_SKYBOX = true;
  37020. break;
  37021. case BABYLON.Texture.SPHERICAL_MODE:
  37022. defines.REFLECTIONMAP_SPHERICAL = true;
  37023. break;
  37024. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37025. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  37026. break;
  37027. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37028. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  37029. break;
  37030. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37031. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  37032. break;
  37033. }
  37034. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  37035. if (reflectionTexture.sphericalPolynomial) {
  37036. defines.USESPHERICALFROMREFLECTIONMAP = true;
  37037. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  37038. defines.USESPHERICALINVERTEX = false;
  37039. }
  37040. else {
  37041. defines.USESPHERICALINVERTEX = true;
  37042. }
  37043. }
  37044. }
  37045. }
  37046. else {
  37047. defines.REFLECTION = false;
  37048. defines.REFLECTIONMAP_3D = false;
  37049. defines.REFLECTIONMAP_SPHERICAL = false;
  37050. defines.REFLECTIONMAP_PLANAR = false;
  37051. defines.REFLECTIONMAP_CUBIC = false;
  37052. defines.REFLECTIONMAP_PROJECTION = false;
  37053. defines.REFLECTIONMAP_SKYBOX = false;
  37054. defines.REFLECTIONMAP_EXPLICIT = false;
  37055. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37056. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37057. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37058. defines.INVERTCUBICMAP = false;
  37059. defines.USESPHERICALFROMREFLECTIONMAP = false;
  37060. defines.USESPHERICALINVERTEX = false;
  37061. defines.REFLECTIONMAP_OPPOSITEZ = false;
  37062. defines.LODINREFLECTIONALPHA = false;
  37063. defines.GAMMAREFLECTION = false;
  37064. }
  37065. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37066. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37067. return false;
  37068. }
  37069. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37070. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37071. }
  37072. else {
  37073. defines.LIGHTMAP = false;
  37074. }
  37075. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37076. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37077. return false;
  37078. }
  37079. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37080. }
  37081. else {
  37082. defines.EMISSIVE = false;
  37083. }
  37084. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37085. if (this._metallicTexture) {
  37086. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  37087. return false;
  37088. }
  37089. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  37090. defines.METALLICWORKFLOW = true;
  37091. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  37092. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  37093. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  37094. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  37095. }
  37096. else if (this._reflectivityTexture) {
  37097. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  37098. return false;
  37099. }
  37100. defines.METALLICWORKFLOW = false;
  37101. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  37102. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  37103. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  37104. }
  37105. else {
  37106. defines.METALLICWORKFLOW = false;
  37107. defines.REFLECTIVITY = false;
  37108. }
  37109. if (this._microSurfaceTexture) {
  37110. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  37111. return false;
  37112. }
  37113. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  37114. }
  37115. else {
  37116. defines.MICROSURFACEMAP = false;
  37117. }
  37118. }
  37119. else {
  37120. defines.REFLECTIVITY = false;
  37121. defines.MICROSURFACEMAP = false;
  37122. }
  37123. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37124. // Bump texure can not be none blocking.
  37125. if (!this._bumpTexture.isReady()) {
  37126. return false;
  37127. }
  37128. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37129. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37130. defines.PARALLAX = true;
  37131. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  37132. }
  37133. else {
  37134. defines.PARALLAX = false;
  37135. }
  37136. }
  37137. else {
  37138. defines.BUMP = false;
  37139. }
  37140. var refractionTexture = this._getRefractionTexture();
  37141. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37142. if (!refractionTexture.isReadyOrNotBlocking()) {
  37143. return false;
  37144. }
  37145. defines.REFRACTION = true;
  37146. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  37147. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  37148. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  37149. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  37150. if (this._linkRefractionWithTransparency) {
  37151. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  37152. }
  37153. }
  37154. else {
  37155. defines.REFRACTION = false;
  37156. }
  37157. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37158. // This is blocking.
  37159. if (!this._environmentBRDFTexture.isReady()) {
  37160. return false;
  37161. }
  37162. defines.ENVIRONMENTBRDF = true;
  37163. }
  37164. else {
  37165. defines.ENVIRONMENTBRDF = false;
  37166. }
  37167. if (this._shouldUseAlphaFromAlbedoTexture()) {
  37168. defines.ALPHAFROMALBEDO = true;
  37169. }
  37170. else {
  37171. defines.ALPHAFROMALBEDO = false;
  37172. }
  37173. }
  37174. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  37175. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  37176. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  37177. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  37178. defines.METALLICWORKFLOW = true;
  37179. }
  37180. else {
  37181. defines.METALLICWORKFLOW = false;
  37182. }
  37183. if (!this.backFaceCulling && this._twoSidedLighting) {
  37184. defines.TWOSIDEDLIGHTING = true;
  37185. }
  37186. else {
  37187. defines.TWOSIDEDLIGHTING = false;
  37188. }
  37189. defines.ALPHATESTVALUE = this._alphaCutOff;
  37190. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  37191. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  37192. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  37193. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  37194. }
  37195. if (defines._areImageProcessingDirty) {
  37196. if (!this._imageProcessingConfiguration.isReady()) {
  37197. return false;
  37198. }
  37199. this._imageProcessingConfiguration.prepareDefines(defines);
  37200. }
  37201. defines.FORCENORMALFORWARD = this._forceNormalForward;
  37202. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  37203. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  37204. // Misc.
  37205. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  37206. // Values that need to be evaluated on every frame
  37207. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest);
  37208. // Attribs
  37209. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  37210. var bufferMesh = null;
  37211. if (mesh instanceof BABYLON.InstancedMesh) {
  37212. bufferMesh = mesh.sourceMesh;
  37213. }
  37214. else if (mesh instanceof BABYLON.Mesh) {
  37215. bufferMesh = mesh;
  37216. }
  37217. if (bufferMesh) {
  37218. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37219. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  37220. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  37221. var normals = normalVertexBuffer.getData();
  37222. var vertexBufferOffset = normalVertexBuffer.getOffset();
  37223. var strideSize = normalVertexBuffer.getStrideSize();
  37224. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  37225. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  37226. defines.NORMAL = false;
  37227. }
  37228. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37229. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  37230. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  37231. var tangents = tangentVertexBuffer.getData();
  37232. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  37233. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  37234. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  37235. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  37236. defines.TANGENT = false;
  37237. }
  37238. }
  37239. }
  37240. else {
  37241. if (!scene.getEngine().getCaps().standardDerivatives) {
  37242. bufferMesh.createNormals(true);
  37243. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  37244. }
  37245. }
  37246. }
  37247. }
  37248. // Get correct effect
  37249. if (defines.isDirty) {
  37250. defines.markAsProcessed();
  37251. scene.resetCachedMaterial();
  37252. // Fallbacks
  37253. var fallbacks = new BABYLON.EffectFallbacks();
  37254. var fallbackRank = 0;
  37255. if (defines.USESPHERICALINVERTEX) {
  37256. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  37257. }
  37258. if (defines.FOG) {
  37259. fallbacks.addFallback(fallbackRank, "FOG");
  37260. }
  37261. if (defines.POINTSIZE) {
  37262. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  37263. }
  37264. if (defines.LOGARITHMICDEPTH) {
  37265. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  37266. }
  37267. if (defines.PARALLAX) {
  37268. fallbacks.addFallback(fallbackRank, "PARALLAX");
  37269. }
  37270. if (defines.PARALLAXOCCLUSION) {
  37271. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  37272. }
  37273. if (defines.ENVIRONMENTBRDF) {
  37274. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  37275. }
  37276. if (defines.TANGENT) {
  37277. fallbacks.addFallback(fallbackRank++, "TANGENT");
  37278. }
  37279. if (defines.BUMP) {
  37280. fallbacks.addFallback(fallbackRank++, "BUMP");
  37281. }
  37282. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  37283. if (defines.SPECULARTERM) {
  37284. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  37285. }
  37286. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  37287. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  37288. }
  37289. if (defines.LIGHTMAP) {
  37290. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  37291. }
  37292. if (defines.NORMAL) {
  37293. fallbacks.addFallback(fallbackRank++, "NORMAL");
  37294. }
  37295. if (defines.AMBIENT) {
  37296. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  37297. }
  37298. if (defines.EMISSIVE) {
  37299. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  37300. }
  37301. if (defines.VERTEXCOLOR) {
  37302. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  37303. }
  37304. if (defines.NUM_BONE_INFLUENCERS > 0) {
  37305. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  37306. }
  37307. if (defines.MORPHTARGETS) {
  37308. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  37309. }
  37310. //Attributes
  37311. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37312. if (defines.NORMAL) {
  37313. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37314. }
  37315. if (defines.TANGENT) {
  37316. attribs.push(BABYLON.VertexBuffer.TangentKind);
  37317. }
  37318. if (defines.UV1) {
  37319. attribs.push(BABYLON.VertexBuffer.UVKind);
  37320. }
  37321. if (defines.UV2) {
  37322. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37323. }
  37324. if (defines.VERTEXCOLOR) {
  37325. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37326. }
  37327. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37328. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37329. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37330. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  37331. "vFogInfos", "vFogColor", "pointSize",
  37332. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37333. "mBones",
  37334. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37335. "vLightingIntensity",
  37336. "logarithmicDepthConstant",
  37337. "vSphericalX", "vSphericalY", "vSphericalZ",
  37338. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  37339. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  37340. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  37341. "vTangentSpaceParams"
  37342. ];
  37343. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  37344. "bumpSampler", "lightmapSampler", "opacitySampler",
  37345. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  37346. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  37347. "microSurfaceSampler", "environmentBrdfSampler"];
  37348. var uniformBuffers = ["Material", "Scene"];
  37349. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37350. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37351. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37352. uniformsNames: uniforms,
  37353. uniformBuffersNames: uniformBuffers,
  37354. samplers: samplers,
  37355. defines: defines,
  37356. maxSimultaneousLights: this._maxSimultaneousLights
  37357. });
  37358. var onCompiled = function (effect) {
  37359. if (_this.onCompiled) {
  37360. _this.onCompiled(effect);
  37361. }
  37362. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  37363. };
  37364. var join = defines.toString();
  37365. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  37366. attributes: attribs,
  37367. uniformsNames: uniforms,
  37368. uniformBuffersNames: uniformBuffers,
  37369. samplers: samplers,
  37370. defines: join,
  37371. fallbacks: fallbacks,
  37372. onCompiled: onCompiled,
  37373. onError: this.onError,
  37374. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37375. }, engine), defines);
  37376. this.buildUniformLayout();
  37377. }
  37378. if (!subMesh.effect || !subMesh.effect.isReady()) {
  37379. return false;
  37380. }
  37381. defines._renderId = scene.getRenderId();
  37382. this._wasPreviouslyReady = true;
  37383. return true;
  37384. };
  37385. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  37386. // Order is important !
  37387. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  37388. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  37389. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37390. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37391. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37392. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  37393. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  37394. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37395. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37396. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37397. this._uniformBuffer.addUniform("albedoMatrix", 16);
  37398. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37399. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37400. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37401. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37402. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  37403. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  37404. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37405. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  37406. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37407. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37408. this._uniformBuffer.addUniform("vReflectionColor", 3);
  37409. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  37410. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  37411. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  37412. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  37413. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  37414. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37415. this._uniformBuffer.addUniform("pointSize", 1);
  37416. this._uniformBuffer.create();
  37417. };
  37418. PBRBaseMaterial.prototype.unbind = function () {
  37419. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37420. this._uniformBuffer.setTexture("reflectionSampler", null);
  37421. }
  37422. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37423. this._uniformBuffer.setTexture("refractionSampler", null);
  37424. }
  37425. _super.prototype.unbind.call(this);
  37426. };
  37427. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37428. this._activeEffect.setMatrix("world", world);
  37429. };
  37430. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37431. var scene = this.getScene();
  37432. var defines = subMesh._materialDefines;
  37433. if (!defines) {
  37434. return;
  37435. }
  37436. var effect = subMesh.effect;
  37437. if (!effect) {
  37438. return;
  37439. }
  37440. this._activeEffect = effect;
  37441. // Matrices
  37442. this.bindOnlyWorldMatrix(world);
  37443. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37444. // Bones
  37445. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  37446. var reflectionTexture = null;
  37447. if (mustRebind) {
  37448. this._uniformBuffer.bindToEffect(effect, "Material");
  37449. this.bindViewProjection(effect);
  37450. reflectionTexture = this._getReflectionTexture();
  37451. var refractionTexture = this._getRefractionTexture();
  37452. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37453. // Texture uniforms
  37454. if (scene.texturesEnabled) {
  37455. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37456. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  37457. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  37458. }
  37459. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37460. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  37461. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37462. }
  37463. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37464. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37465. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37466. }
  37467. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37468. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  37469. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  37470. var polynomials = reflectionTexture.sphericalPolynomial;
  37471. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  37472. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  37473. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  37474. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  37475. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  37476. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  37477. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  37478. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  37479. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  37480. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  37481. }
  37482. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  37483. }
  37484. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37485. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37486. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37487. }
  37488. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37489. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37490. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37491. }
  37492. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37493. if (this._metallicTexture) {
  37494. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  37495. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  37496. }
  37497. else if (this._reflectivityTexture) {
  37498. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  37499. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  37500. }
  37501. if (this._microSurfaceTexture) {
  37502. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  37503. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  37504. }
  37505. }
  37506. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37507. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  37508. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37509. if (scene._mirroredCameraPosition) {
  37510. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37511. }
  37512. else {
  37513. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37514. }
  37515. }
  37516. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37517. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  37518. var depth = 1.0;
  37519. if (!refractionTexture.isCube) {
  37520. if (refractionTexture.depth) {
  37521. depth = refractionTexture.depth;
  37522. }
  37523. }
  37524. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  37525. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  37526. }
  37527. }
  37528. // Point size
  37529. if (this.pointsCloud) {
  37530. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37531. }
  37532. // Colors
  37533. if (defines.METALLICWORKFLOW) {
  37534. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  37535. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  37536. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  37537. }
  37538. else {
  37539. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  37540. }
  37541. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  37542. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  37543. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  37544. // Misc
  37545. this._lightingInfos.x = this._directIntensity;
  37546. this._lightingInfos.y = this._emissiveIntensity;
  37547. this._lightingInfos.z = this._environmentIntensity;
  37548. this._lightingInfos.w = this._specularIntensity;
  37549. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  37550. }
  37551. // Textures
  37552. if (scene.texturesEnabled) {
  37553. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37554. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  37555. }
  37556. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37557. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  37558. }
  37559. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37560. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  37561. }
  37562. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37563. if (defines.LODBASEDMICROSFURACE) {
  37564. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  37565. }
  37566. else {
  37567. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  37568. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  37569. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  37570. }
  37571. }
  37572. if (defines.ENVIRONMENTBRDF) {
  37573. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  37574. }
  37575. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37576. if (defines.LODBASEDMICROSFURACE) {
  37577. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  37578. }
  37579. else {
  37580. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  37581. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  37582. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  37583. }
  37584. }
  37585. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37586. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  37587. }
  37588. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37589. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  37590. }
  37591. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37592. if (this._metallicTexture) {
  37593. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  37594. }
  37595. else if (this._reflectivityTexture) {
  37596. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  37597. }
  37598. if (this._microSurfaceTexture) {
  37599. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  37600. }
  37601. }
  37602. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37603. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  37604. }
  37605. }
  37606. // Clip plane
  37607. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  37608. // Colors
  37609. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  37610. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37611. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  37612. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  37613. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37614. }
  37615. if (mustRebind || !this.isFrozen) {
  37616. // Lights
  37617. if (scene.lightsEnabled && !this._disableLighting) {
  37618. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  37619. }
  37620. // View
  37621. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  37622. this.bindView(effect);
  37623. }
  37624. // Fog
  37625. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  37626. // Morph targets
  37627. if (defines.NUM_MORPH_INFLUENCERS) {
  37628. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  37629. }
  37630. // image processing
  37631. this._imageProcessingConfiguration.bind(this._activeEffect);
  37632. // Log. depth
  37633. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  37634. }
  37635. this._uniformBuffer.update();
  37636. this._afterBind(mesh);
  37637. };
  37638. PBRBaseMaterial.prototype.getAnimatables = function () {
  37639. var results = [];
  37640. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  37641. results.push(this._albedoTexture);
  37642. }
  37643. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37644. results.push(this._ambientTexture);
  37645. }
  37646. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37647. results.push(this._opacityTexture);
  37648. }
  37649. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37650. results.push(this._reflectionTexture);
  37651. }
  37652. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37653. results.push(this._emissiveTexture);
  37654. }
  37655. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  37656. results.push(this._metallicTexture);
  37657. }
  37658. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  37659. results.push(this._reflectivityTexture);
  37660. }
  37661. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37662. results.push(this._bumpTexture);
  37663. }
  37664. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37665. results.push(this._lightmapTexture);
  37666. }
  37667. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37668. results.push(this._refractionTexture);
  37669. }
  37670. return results;
  37671. };
  37672. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  37673. if (this._reflectionTexture) {
  37674. return this._reflectionTexture;
  37675. }
  37676. return this.getScene().environmentTexture;
  37677. };
  37678. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  37679. if (this._refractionTexture) {
  37680. return this._refractionTexture;
  37681. }
  37682. if (this._linkRefractionWithTransparency) {
  37683. return this.getScene().environmentTexture;
  37684. }
  37685. return null;
  37686. };
  37687. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37688. if (forceDisposeTextures) {
  37689. if (this._albedoTexture) {
  37690. this._albedoTexture.dispose();
  37691. }
  37692. if (this._ambientTexture) {
  37693. this._ambientTexture.dispose();
  37694. }
  37695. if (this._opacityTexture) {
  37696. this._opacityTexture.dispose();
  37697. }
  37698. if (this._reflectionTexture) {
  37699. this._reflectionTexture.dispose();
  37700. }
  37701. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  37702. this._environmentBRDFTexture.dispose();
  37703. }
  37704. if (this._emissiveTexture) {
  37705. this._emissiveTexture.dispose();
  37706. }
  37707. if (this._metallicTexture) {
  37708. this._metallicTexture.dispose();
  37709. }
  37710. if (this._reflectivityTexture) {
  37711. this._reflectivityTexture.dispose();
  37712. }
  37713. if (this._bumpTexture) {
  37714. this._bumpTexture.dispose();
  37715. }
  37716. if (this._lightmapTexture) {
  37717. this._lightmapTexture.dispose();
  37718. }
  37719. if (this._refractionTexture) {
  37720. this._refractionTexture.dispose();
  37721. }
  37722. }
  37723. this._renderTargets.dispose();
  37724. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37725. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37726. }
  37727. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37728. };
  37729. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  37730. __decorate([
  37731. BABYLON.serializeAsImageProcessingConfiguration()
  37732. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  37733. __decorate([
  37734. BABYLON.serialize()
  37735. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  37736. __decorate([
  37737. BABYLON.serialize()
  37738. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  37739. return PBRBaseMaterial;
  37740. }(BABYLON.PushMaterial));
  37741. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  37742. })(BABYLON || (BABYLON = {}));
  37743. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  37744. var BABYLON;
  37745. (function (BABYLON) {
  37746. /**
  37747. * The Physically based simple base material of BJS.
  37748. *
  37749. * This enables better naming and convention enforcements on top of the pbrMaterial.
  37750. * It is used as the base class for both the specGloss and metalRough conventions.
  37751. */
  37752. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  37753. __extends(PBRBaseSimpleMaterial, _super);
  37754. /**
  37755. * Instantiates a new PBRMaterial instance.
  37756. *
  37757. * @param name The material name
  37758. * @param scene The scene the material will be use in.
  37759. */
  37760. function PBRBaseSimpleMaterial(name, scene) {
  37761. var _this = _super.call(this, name, scene) || this;
  37762. /**
  37763. * Number of Simultaneous lights allowed on the material.
  37764. */
  37765. _this.maxSimultaneousLights = 4;
  37766. /**
  37767. * If sets to true, disables all the lights affecting the material.
  37768. */
  37769. _this.disableLighting = false;
  37770. /**
  37771. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37772. */
  37773. _this.invertNormalMapX = false;
  37774. /**
  37775. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37776. */
  37777. _this.invertNormalMapY = false;
  37778. /**
  37779. * Emissivie color used to self-illuminate the model.
  37780. */
  37781. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37782. /**
  37783. * Occlusion Channel Strenght.
  37784. */
  37785. _this.occlusionStrength = 1.0;
  37786. _this.useLightmapAsShadowmap = false;
  37787. _this._useAlphaFromAlbedoTexture = true;
  37788. _this._useAmbientInGrayScale = true;
  37789. return _this;
  37790. }
  37791. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  37792. /**
  37793. * Gets the current double sided mode.
  37794. */
  37795. get: function () {
  37796. return this._twoSidedLighting;
  37797. },
  37798. /**
  37799. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37800. */
  37801. set: function (value) {
  37802. if (this._twoSidedLighting === value) {
  37803. return;
  37804. }
  37805. this._twoSidedLighting = value;
  37806. this.backFaceCulling = !value;
  37807. this._markAllSubMeshesAsTexturesDirty();
  37808. },
  37809. enumerable: true,
  37810. configurable: true
  37811. });
  37812. /**
  37813. * Return the active textures of the material.
  37814. */
  37815. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  37816. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37817. if (this.environmentTexture) {
  37818. activeTextures.push(this.environmentTexture);
  37819. }
  37820. if (this.normalTexture) {
  37821. activeTextures.push(this.normalTexture);
  37822. }
  37823. if (this.emissiveTexture) {
  37824. activeTextures.push(this.emissiveTexture);
  37825. }
  37826. if (this.occlusionTexture) {
  37827. activeTextures.push(this.occlusionTexture);
  37828. }
  37829. if (this.lightmapTexture) {
  37830. activeTextures.push(this.lightmapTexture);
  37831. }
  37832. return activeTextures;
  37833. };
  37834. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  37835. if (_super.prototype.hasTexture.call(this, texture)) {
  37836. return true;
  37837. }
  37838. if (this.lightmapTexture === texture) {
  37839. return true;
  37840. }
  37841. return false;
  37842. };
  37843. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  37844. return "PBRBaseSimpleMaterial";
  37845. };
  37846. __decorate([
  37847. BABYLON.serialize(),
  37848. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37849. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  37850. __decorate([
  37851. BABYLON.serialize(),
  37852. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37853. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  37854. __decorate([
  37855. BABYLON.serializeAsTexture(),
  37856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  37857. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  37858. __decorate([
  37859. BABYLON.serialize(),
  37860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37861. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  37862. __decorate([
  37863. BABYLON.serialize(),
  37864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37865. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  37866. __decorate([
  37867. BABYLON.serializeAsTexture(),
  37868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  37869. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  37870. __decorate([
  37871. BABYLON.serializeAsColor3("emissive"),
  37872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37873. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  37874. __decorate([
  37875. BABYLON.serializeAsTexture(),
  37876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37877. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  37878. __decorate([
  37879. BABYLON.serialize(),
  37880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  37881. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  37882. __decorate([
  37883. BABYLON.serializeAsTexture(),
  37884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  37885. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  37886. __decorate([
  37887. BABYLON.serialize(),
  37888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  37889. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  37890. __decorate([
  37891. BABYLON.serialize()
  37892. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  37893. __decorate([
  37894. BABYLON.serializeAsTexture(),
  37895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37896. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  37897. __decorate([
  37898. BABYLON.serialize(),
  37899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37900. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37901. return PBRBaseSimpleMaterial;
  37902. }(BABYLON.PBRBaseMaterial));
  37903. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  37904. })(BABYLON || (BABYLON = {}));
  37905. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  37906. var BABYLON;
  37907. (function (BABYLON) {
  37908. /**
  37909. * The Physically based material of BJS.
  37910. *
  37911. * This offers the main features of a standard PBR material.
  37912. * For more information, please refer to the documentation :
  37913. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37914. */
  37915. var PBRMaterial = /** @class */ (function (_super) {
  37916. __extends(PBRMaterial, _super);
  37917. /**
  37918. * Instantiates a new PBRMaterial instance.
  37919. *
  37920. * @param name The material name
  37921. * @param scene The scene the material will be use in.
  37922. */
  37923. function PBRMaterial(name, scene) {
  37924. var _this = _super.call(this, name, scene) || this;
  37925. /**
  37926. * Intensity of the direct lights e.g. the four lights available in your scene.
  37927. * This impacts both the direct diffuse and specular highlights.
  37928. */
  37929. _this.directIntensity = 1.0;
  37930. /**
  37931. * Intensity of the emissive part of the material.
  37932. * This helps controlling the emissive effect without modifying the emissive color.
  37933. */
  37934. _this.emissiveIntensity = 1.0;
  37935. /**
  37936. * Intensity of the environment e.g. how much the environment will light the object
  37937. * either through harmonics for rough material or through the refelction for shiny ones.
  37938. */
  37939. _this.environmentIntensity = 1.0;
  37940. /**
  37941. * This is a special control allowing the reduction of the specular highlights coming from the
  37942. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37943. */
  37944. _this.specularIntensity = 1.0;
  37945. /**
  37946. * Debug Control allowing disabling the bump map on this material.
  37947. */
  37948. _this.disableBumpMap = false;
  37949. /**
  37950. * AKA Occlusion Texture Intensity in other nomenclature.
  37951. */
  37952. _this.ambientTextureStrength = 1.0;
  37953. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  37954. /**
  37955. * AKA Diffuse Color in other nomenclature.
  37956. */
  37957. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  37958. /**
  37959. * AKA Specular Color in other nomenclature.
  37960. */
  37961. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37962. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  37963. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37964. /**
  37965. * AKA Glossiness in other nomenclature.
  37966. */
  37967. _this.microSurface = 1.0;
  37968. /**
  37969. * source material index of refraction (IOR)' / 'destination material IOR.
  37970. */
  37971. _this.indexOfRefraction = 0.66;
  37972. /**
  37973. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37974. */
  37975. _this.invertRefractionY = false;
  37976. /**
  37977. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37978. * Materials half opaque for instance using refraction could benefit from this control.
  37979. */
  37980. _this.linkRefractionWithTransparency = false;
  37981. _this.useLightmapAsShadowmap = false;
  37982. /**
  37983. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37984. */
  37985. _this.useAlphaFromAlbedoTexture = false;
  37986. /**
  37987. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37988. */
  37989. _this.forceAlphaTest = false;
  37990. /**
  37991. * Defines the alpha limits in alpha test mode.
  37992. */
  37993. _this.alphaCutOff = 0.4;
  37994. /**
  37995. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37996. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37997. */
  37998. _this.useSpecularOverAlpha = true;
  37999. /**
  38000. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38001. */
  38002. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  38003. /**
  38004. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38005. */
  38006. _this.useRoughnessFromMetallicTextureAlpha = true;
  38007. /**
  38008. * Specifies if the metallic texture contains the roughness information in its green channel.
  38009. */
  38010. _this.useRoughnessFromMetallicTextureGreen = false;
  38011. /**
  38012. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38013. */
  38014. _this.useMetallnessFromMetallicTextureBlue = false;
  38015. /**
  38016. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38017. */
  38018. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  38019. /**
  38020. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38021. */
  38022. _this.useAmbientInGrayScale = false;
  38023. /**
  38024. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38025. * The material will try to infer what glossiness each pixel should be.
  38026. */
  38027. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  38028. /**
  38029. * BJS is using an harcoded light falloff based on a manually sets up range.
  38030. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38031. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38032. */
  38033. _this.usePhysicalLightFalloff = true;
  38034. /**
  38035. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38036. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38037. */
  38038. _this.useRadianceOverAlpha = true;
  38039. /**
  38040. * Allows using the bump map in parallax mode.
  38041. */
  38042. _this.useParallax = false;
  38043. /**
  38044. * Allows using the bump map in parallax occlusion mode.
  38045. */
  38046. _this.useParallaxOcclusion = false;
  38047. /**
  38048. * Controls the scale bias of the parallax mode.
  38049. */
  38050. _this.parallaxScaleBias = 0.05;
  38051. /**
  38052. * If sets to true, disables all the lights affecting the material.
  38053. */
  38054. _this.disableLighting = false;
  38055. /**
  38056. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38057. */
  38058. _this.forceIrradianceInFragment = false;
  38059. /**
  38060. * Number of Simultaneous lights allowed on the material.
  38061. */
  38062. _this.maxSimultaneousLights = 4;
  38063. /**
  38064. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38065. */
  38066. _this.invertNormalMapX = false;
  38067. /**
  38068. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38069. */
  38070. _this.invertNormalMapY = false;
  38071. /**
  38072. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38073. */
  38074. _this.twoSidedLighting = false;
  38075. /**
  38076. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38077. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  38078. */
  38079. _this.useAlphaFresnel = false;
  38080. /**
  38081. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38082. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  38083. */
  38084. _this.useLinearAlphaFresnel = false;
  38085. /**
  38086. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38087. * And/Or occlude the blended part.
  38088. */
  38089. _this.environmentBRDFTexture = null;
  38090. /**
  38091. * Force normal to face away from face.
  38092. */
  38093. _this.forceNormalForward = false;
  38094. /**
  38095. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  38096. * makes the reflect vector face the model (under horizon).
  38097. */
  38098. _this.useHorizonOcclusion = true;
  38099. /**
  38100. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  38101. * too much the area relying on ambient texture to define their ambient occlusion.
  38102. */
  38103. _this.useRadianceOcclusion = true;
  38104. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38105. return _this;
  38106. }
  38107. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  38108. /**
  38109. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  38110. */
  38111. get: function () {
  38112. return this._PBRMATERIAL_OPAQUE;
  38113. },
  38114. enumerable: true,
  38115. configurable: true
  38116. });
  38117. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  38118. /**
  38119. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  38120. */
  38121. get: function () {
  38122. return this._PBRMATERIAL_ALPHATEST;
  38123. },
  38124. enumerable: true,
  38125. configurable: true
  38126. });
  38127. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  38128. /**
  38129. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38130. */
  38131. get: function () {
  38132. return this._PBRMATERIAL_ALPHABLEND;
  38133. },
  38134. enumerable: true,
  38135. configurable: true
  38136. });
  38137. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  38138. /**
  38139. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38140. * They are also discarded below the alpha cutoff threshold to improve performances.
  38141. */
  38142. get: function () {
  38143. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  38144. },
  38145. enumerable: true,
  38146. configurable: true
  38147. });
  38148. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  38149. /**
  38150. * Gets the image processing configuration used either in this material.
  38151. */
  38152. get: function () {
  38153. return this._imageProcessingConfiguration;
  38154. },
  38155. /**
  38156. * Sets the Default image processing configuration used either in the this material.
  38157. *
  38158. * If sets to null, the scene one is in use.
  38159. */
  38160. set: function (value) {
  38161. this._attachImageProcessingConfiguration(value);
  38162. // Ensure the effect will be rebuilt.
  38163. this._markAllSubMeshesAsTexturesDirty();
  38164. },
  38165. enumerable: true,
  38166. configurable: true
  38167. });
  38168. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  38169. /**
  38170. * Gets wether the color curves effect is enabled.
  38171. */
  38172. get: function () {
  38173. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38174. },
  38175. /**
  38176. * Sets wether the color curves effect is enabled.
  38177. */
  38178. set: function (value) {
  38179. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38180. },
  38181. enumerable: true,
  38182. configurable: true
  38183. });
  38184. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  38185. /**
  38186. * Gets wether the color grading effect is enabled.
  38187. */
  38188. get: function () {
  38189. return this.imageProcessingConfiguration.colorGradingEnabled;
  38190. },
  38191. /**
  38192. * Gets wether the color grading effect is enabled.
  38193. */
  38194. set: function (value) {
  38195. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38196. },
  38197. enumerable: true,
  38198. configurable: true
  38199. });
  38200. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  38201. /**
  38202. * Gets wether tonemapping is enabled or not.
  38203. */
  38204. get: function () {
  38205. return this._imageProcessingConfiguration.toneMappingEnabled;
  38206. },
  38207. /**
  38208. * Sets wether tonemapping is enabled or not
  38209. */
  38210. set: function (value) {
  38211. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38212. },
  38213. enumerable: true,
  38214. configurable: true
  38215. });
  38216. ;
  38217. ;
  38218. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  38219. /**
  38220. * The camera exposure used on this material.
  38221. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38222. * This corresponds to a photographic exposure.
  38223. */
  38224. get: function () {
  38225. return this._imageProcessingConfiguration.exposure;
  38226. },
  38227. /**
  38228. * The camera exposure used on this material.
  38229. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38230. * This corresponds to a photographic exposure.
  38231. */
  38232. set: function (value) {
  38233. this._imageProcessingConfiguration.exposure = value;
  38234. },
  38235. enumerable: true,
  38236. configurable: true
  38237. });
  38238. ;
  38239. ;
  38240. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  38241. /**
  38242. * Gets The camera contrast used on this material.
  38243. */
  38244. get: function () {
  38245. return this._imageProcessingConfiguration.contrast;
  38246. },
  38247. /**
  38248. * Sets The camera contrast used on this material.
  38249. */
  38250. set: function (value) {
  38251. this._imageProcessingConfiguration.contrast = value;
  38252. },
  38253. enumerable: true,
  38254. configurable: true
  38255. });
  38256. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  38257. /**
  38258. * Gets the Color Grading 2D Lookup Texture.
  38259. */
  38260. get: function () {
  38261. return this._imageProcessingConfiguration.colorGradingTexture;
  38262. },
  38263. /**
  38264. * Sets the Color Grading 2D Lookup Texture.
  38265. */
  38266. set: function (value) {
  38267. this._imageProcessingConfiguration.colorGradingTexture = value;
  38268. },
  38269. enumerable: true,
  38270. configurable: true
  38271. });
  38272. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  38273. /**
  38274. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38275. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38276. * 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;
  38277. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38278. */
  38279. get: function () {
  38280. return this._imageProcessingConfiguration.colorCurves;
  38281. },
  38282. /**
  38283. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38284. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38285. * 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;
  38286. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38287. */
  38288. set: function (value) {
  38289. this._imageProcessingConfiguration.colorCurves = value;
  38290. },
  38291. enumerable: true,
  38292. configurable: true
  38293. });
  38294. PBRMaterial.prototype.getClassName = function () {
  38295. return "PBRMaterial";
  38296. };
  38297. PBRMaterial.prototype.getActiveTextures = function () {
  38298. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38299. if (this._albedoTexture) {
  38300. activeTextures.push(this._albedoTexture);
  38301. }
  38302. if (this._ambientTexture) {
  38303. activeTextures.push(this._ambientTexture);
  38304. }
  38305. if (this._opacityTexture) {
  38306. activeTextures.push(this._opacityTexture);
  38307. }
  38308. if (this._reflectionTexture) {
  38309. activeTextures.push(this._reflectionTexture);
  38310. }
  38311. if (this._emissiveTexture) {
  38312. activeTextures.push(this._emissiveTexture);
  38313. }
  38314. if (this._reflectivityTexture) {
  38315. activeTextures.push(this._reflectivityTexture);
  38316. }
  38317. if (this._metallicTexture) {
  38318. activeTextures.push(this._metallicTexture);
  38319. }
  38320. if (this._microSurfaceTexture) {
  38321. activeTextures.push(this._microSurfaceTexture);
  38322. }
  38323. if (this._bumpTexture) {
  38324. activeTextures.push(this._bumpTexture);
  38325. }
  38326. if (this._lightmapTexture) {
  38327. activeTextures.push(this._lightmapTexture);
  38328. }
  38329. if (this._refractionTexture) {
  38330. activeTextures.push(this._refractionTexture);
  38331. }
  38332. return activeTextures;
  38333. };
  38334. PBRMaterial.prototype.hasTexture = function (texture) {
  38335. if (_super.prototype.hasTexture.call(this, texture)) {
  38336. return true;
  38337. }
  38338. if (this._albedoTexture === texture) {
  38339. return true;
  38340. }
  38341. if (this._ambientTexture === texture) {
  38342. return true;
  38343. }
  38344. if (this._opacityTexture === texture) {
  38345. return true;
  38346. }
  38347. if (this._reflectionTexture === texture) {
  38348. return true;
  38349. }
  38350. if (this._reflectivityTexture === texture) {
  38351. return true;
  38352. }
  38353. if (this._metallicTexture === texture) {
  38354. return true;
  38355. }
  38356. if (this._microSurfaceTexture === texture) {
  38357. return true;
  38358. }
  38359. if (this._bumpTexture === texture) {
  38360. return true;
  38361. }
  38362. if (this._lightmapTexture === texture) {
  38363. return true;
  38364. }
  38365. if (this._refractionTexture === texture) {
  38366. return true;
  38367. }
  38368. return false;
  38369. };
  38370. PBRMaterial.prototype.clone = function (name) {
  38371. var _this = this;
  38372. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  38373. clone.id = name;
  38374. clone.name = name;
  38375. return clone;
  38376. };
  38377. PBRMaterial.prototype.serialize = function () {
  38378. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38379. serializationObject.customType = "BABYLON.PBRMaterial";
  38380. return serializationObject;
  38381. };
  38382. // Statics
  38383. PBRMaterial.Parse = function (source, scene, rootUrl) {
  38384. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  38385. };
  38386. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  38387. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  38388. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  38389. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  38390. __decorate([
  38391. BABYLON.serialize(),
  38392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38393. ], PBRMaterial.prototype, "directIntensity", void 0);
  38394. __decorate([
  38395. BABYLON.serialize(),
  38396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38397. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  38398. __decorate([
  38399. BABYLON.serialize(),
  38400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38401. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  38402. __decorate([
  38403. BABYLON.serialize(),
  38404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38405. ], PBRMaterial.prototype, "specularIntensity", void 0);
  38406. __decorate([
  38407. BABYLON.serialize(),
  38408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38409. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  38410. __decorate([
  38411. BABYLON.serializeAsTexture(),
  38412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38413. ], PBRMaterial.prototype, "albedoTexture", void 0);
  38414. __decorate([
  38415. BABYLON.serializeAsTexture(),
  38416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38417. ], PBRMaterial.prototype, "ambientTexture", void 0);
  38418. __decorate([
  38419. BABYLON.serialize(),
  38420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38421. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  38422. __decorate([
  38423. BABYLON.serializeAsTexture(),
  38424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38425. ], PBRMaterial.prototype, "opacityTexture", void 0);
  38426. __decorate([
  38427. BABYLON.serializeAsTexture(),
  38428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38429. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  38430. __decorate([
  38431. BABYLON.serializeAsTexture(),
  38432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38433. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  38434. __decorate([
  38435. BABYLON.serializeAsTexture(),
  38436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38437. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  38438. __decorate([
  38439. BABYLON.serializeAsTexture(),
  38440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38441. ], PBRMaterial.prototype, "metallicTexture", void 0);
  38442. __decorate([
  38443. BABYLON.serialize(),
  38444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38445. ], PBRMaterial.prototype, "metallic", void 0);
  38446. __decorate([
  38447. BABYLON.serialize(),
  38448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38449. ], PBRMaterial.prototype, "roughness", void 0);
  38450. __decorate([
  38451. BABYLON.serializeAsTexture(),
  38452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38453. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  38454. __decorate([
  38455. BABYLON.serializeAsTexture(),
  38456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38457. ], PBRMaterial.prototype, "bumpTexture", void 0);
  38458. __decorate([
  38459. BABYLON.serializeAsTexture(),
  38460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38461. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  38462. __decorate([
  38463. BABYLON.serializeAsTexture(),
  38464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38465. ], PBRMaterial.prototype, "refractionTexture", void 0);
  38466. __decorate([
  38467. BABYLON.serializeAsColor3("ambient"),
  38468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38469. ], PBRMaterial.prototype, "ambientColor", void 0);
  38470. __decorate([
  38471. BABYLON.serializeAsColor3("albedo"),
  38472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38473. ], PBRMaterial.prototype, "albedoColor", void 0);
  38474. __decorate([
  38475. BABYLON.serializeAsColor3("reflectivity"),
  38476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38477. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  38478. __decorate([
  38479. BABYLON.serializeAsColor3("reflection"),
  38480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38481. ], PBRMaterial.prototype, "reflectionColor", void 0);
  38482. __decorate([
  38483. BABYLON.serializeAsColor3("emissive"),
  38484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38485. ], PBRMaterial.prototype, "emissiveColor", void 0);
  38486. __decorate([
  38487. BABYLON.serialize(),
  38488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38489. ], PBRMaterial.prototype, "microSurface", void 0);
  38490. __decorate([
  38491. BABYLON.serialize(),
  38492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38493. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  38494. __decorate([
  38495. BABYLON.serialize(),
  38496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38497. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  38498. __decorate([
  38499. BABYLON.serialize(),
  38500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38501. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  38502. __decorate([
  38503. BABYLON.serialize(),
  38504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38505. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38506. __decorate([
  38507. BABYLON.serialize(),
  38508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38509. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  38510. __decorate([
  38511. BABYLON.serialize(),
  38512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38513. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  38514. __decorate([
  38515. BABYLON.serialize(),
  38516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38517. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  38518. __decorate([
  38519. BABYLON.serialize(),
  38520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38521. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  38522. __decorate([
  38523. BABYLON.serialize(),
  38524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38525. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  38526. __decorate([
  38527. BABYLON.serialize(),
  38528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38529. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  38530. __decorate([
  38531. BABYLON.serialize(),
  38532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38533. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  38534. __decorate([
  38535. BABYLON.serialize(),
  38536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38537. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  38538. __decorate([
  38539. BABYLON.serialize(),
  38540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38541. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  38542. __decorate([
  38543. BABYLON.serialize(),
  38544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38545. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  38546. __decorate([
  38547. BABYLON.serialize(),
  38548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38549. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  38550. __decorate([
  38551. BABYLON.serialize(),
  38552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38553. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  38554. __decorate([
  38555. BABYLON.serialize(),
  38556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38557. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  38558. __decorate([
  38559. BABYLON.serialize(),
  38560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38561. ], PBRMaterial.prototype, "useParallax", void 0);
  38562. __decorate([
  38563. BABYLON.serialize(),
  38564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38565. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  38566. __decorate([
  38567. BABYLON.serialize(),
  38568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38569. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  38570. __decorate([
  38571. BABYLON.serialize(),
  38572. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38573. ], PBRMaterial.prototype, "disableLighting", void 0);
  38574. __decorate([
  38575. BABYLON.serialize(),
  38576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38577. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  38578. __decorate([
  38579. BABYLON.serialize(),
  38580. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38581. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  38582. __decorate([
  38583. BABYLON.serialize(),
  38584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38585. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  38586. __decorate([
  38587. BABYLON.serialize(),
  38588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38589. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  38590. __decorate([
  38591. BABYLON.serialize(),
  38592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38593. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  38594. __decorate([
  38595. BABYLON.serialize(),
  38596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38597. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  38598. __decorate([
  38599. BABYLON.serialize(),
  38600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38601. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  38602. __decorate([
  38603. BABYLON.serializeAsTexture(),
  38604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38605. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  38606. __decorate([
  38607. BABYLON.serialize(),
  38608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38609. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  38610. __decorate([
  38611. BABYLON.serialize(),
  38612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38613. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  38614. __decorate([
  38615. BABYLON.serialize(),
  38616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38617. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  38618. return PBRMaterial;
  38619. }(BABYLON.PBRBaseMaterial));
  38620. BABYLON.PBRMaterial = PBRMaterial;
  38621. })(BABYLON || (BABYLON = {}));
  38622. //# sourceMappingURL=babylon.pbrMaterial.js.map
  38623. var BABYLON;
  38624. (function (BABYLON) {
  38625. /**
  38626. * The PBR material of BJS following the metal roughness convention.
  38627. *
  38628. * This fits to the PBR convention in the GLTF definition:
  38629. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  38630. */
  38631. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  38632. __extends(PBRMetallicRoughnessMaterial, _super);
  38633. /**
  38634. * Instantiates a new PBRMetalRoughnessMaterial instance.
  38635. *
  38636. * @param name The material name
  38637. * @param scene The scene the material will be use in.
  38638. */
  38639. function PBRMetallicRoughnessMaterial(name, scene) {
  38640. var _this = _super.call(this, name, scene) || this;
  38641. _this._useRoughnessFromMetallicTextureAlpha = false;
  38642. _this._useRoughnessFromMetallicTextureGreen = true;
  38643. _this._useMetallnessFromMetallicTextureBlue = true;
  38644. _this._forceMetallicWorkflow = true;
  38645. return _this;
  38646. }
  38647. /**
  38648. * Return the currrent class name of the material.
  38649. */
  38650. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  38651. return "PBRMetallicRoughnessMaterial";
  38652. };
  38653. /**
  38654. * Return the active textures of the material.
  38655. */
  38656. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  38657. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38658. if (this.baseTexture) {
  38659. activeTextures.push(this.baseTexture);
  38660. }
  38661. if (this.metallicRoughnessTexture) {
  38662. activeTextures.push(this.metallicRoughnessTexture);
  38663. }
  38664. return activeTextures;
  38665. };
  38666. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  38667. if (_super.prototype.hasTexture.call(this, texture)) {
  38668. return true;
  38669. }
  38670. if (this.baseTexture === texture) {
  38671. return true;
  38672. }
  38673. if (this.metallicRoughnessTexture === texture) {
  38674. return true;
  38675. }
  38676. return false;
  38677. };
  38678. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  38679. var _this = this;
  38680. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  38681. clone.id = name;
  38682. clone.name = name;
  38683. return clone;
  38684. };
  38685. /**
  38686. * Serialize the material to a parsable JSON object.
  38687. */
  38688. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  38689. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38690. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  38691. return serializationObject;
  38692. };
  38693. /**
  38694. * Parses a JSON object correponding to the serialize function.
  38695. */
  38696. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  38697. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  38698. };
  38699. __decorate([
  38700. BABYLON.serializeAsColor3(),
  38701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38702. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  38703. __decorate([
  38704. BABYLON.serializeAsTexture(),
  38705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38706. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  38707. __decorate([
  38708. BABYLON.serialize(),
  38709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38710. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  38711. __decorate([
  38712. BABYLON.serialize(),
  38713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38714. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  38715. __decorate([
  38716. BABYLON.serializeAsTexture(),
  38717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  38718. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  38719. return PBRMetallicRoughnessMaterial;
  38720. }(BABYLON.PBRBaseSimpleMaterial));
  38721. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  38722. })(BABYLON || (BABYLON = {}));
  38723. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  38724. var BABYLON;
  38725. (function (BABYLON) {
  38726. /**
  38727. * The PBR material of BJS following the specular glossiness convention.
  38728. *
  38729. * This fits to the PBR convention in the GLTF definition:
  38730. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  38731. */
  38732. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  38733. __extends(PBRSpecularGlossinessMaterial, _super);
  38734. /**
  38735. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  38736. *
  38737. * @param name The material name
  38738. * @param scene The scene the material will be use in.
  38739. */
  38740. function PBRSpecularGlossinessMaterial(name, scene) {
  38741. var _this = _super.call(this, name, scene) || this;
  38742. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  38743. return _this;
  38744. }
  38745. /**
  38746. * Return the currrent class name of the material.
  38747. */
  38748. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  38749. return "PBRSpecularGlossinessMaterial";
  38750. };
  38751. /**
  38752. * Return the active textures of the material.
  38753. */
  38754. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  38755. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38756. if (this.diffuseTexture) {
  38757. activeTextures.push(this.diffuseTexture);
  38758. }
  38759. if (this.specularGlossinessTexture) {
  38760. activeTextures.push(this.specularGlossinessTexture);
  38761. }
  38762. return activeTextures;
  38763. };
  38764. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  38765. if (_super.prototype.hasTexture.call(this, texture)) {
  38766. return true;
  38767. }
  38768. if (this.diffuseTexture === texture) {
  38769. return true;
  38770. }
  38771. if (this.specularGlossinessTexture === texture) {
  38772. return true;
  38773. }
  38774. return false;
  38775. };
  38776. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  38777. var _this = this;
  38778. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  38779. clone.id = name;
  38780. clone.name = name;
  38781. return clone;
  38782. };
  38783. /**
  38784. * Serialize the material to a parsable JSON object.
  38785. */
  38786. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  38787. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38788. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  38789. return serializationObject;
  38790. };
  38791. /**
  38792. * Parses a JSON object correponding to the serialize function.
  38793. */
  38794. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  38795. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  38796. };
  38797. __decorate([
  38798. BABYLON.serializeAsColor3("diffuse"),
  38799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38800. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  38801. __decorate([
  38802. BABYLON.serializeAsTexture(),
  38803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38804. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  38805. __decorate([
  38806. BABYLON.serializeAsColor3("specular"),
  38807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  38808. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  38809. __decorate([
  38810. BABYLON.serialize(),
  38811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  38812. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  38813. __decorate([
  38814. BABYLON.serializeAsTexture(),
  38815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  38816. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  38817. return PBRSpecularGlossinessMaterial;
  38818. }(BABYLON.PBRBaseSimpleMaterial));
  38819. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  38820. })(BABYLON || (BABYLON = {}));
  38821. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  38822. var BABYLON;
  38823. (function (BABYLON) {
  38824. BABYLON.CameraInputTypes = {};
  38825. var CameraInputsManager = /** @class */ (function () {
  38826. function CameraInputsManager(camera) {
  38827. this.attached = {};
  38828. this.camera = camera;
  38829. this.checkInputs = function () { };
  38830. }
  38831. CameraInputsManager.prototype.add = function (input) {
  38832. var type = input.getSimpleName();
  38833. if (this.attached[type]) {
  38834. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  38835. return;
  38836. }
  38837. this.attached[type] = input;
  38838. input.camera = this.camera;
  38839. //for checkInputs, we are dynamically creating a function
  38840. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  38841. if (input.checkInputs) {
  38842. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38843. }
  38844. if (this.attachedElement) {
  38845. input.attachControl(this.attachedElement);
  38846. }
  38847. };
  38848. CameraInputsManager.prototype.remove = function (inputToRemove) {
  38849. for (var cam in this.attached) {
  38850. var input = this.attached[cam];
  38851. if (input === inputToRemove) {
  38852. input.detachControl(this.attachedElement);
  38853. input.camera = null;
  38854. delete this.attached[cam];
  38855. this.rebuildInputCheck();
  38856. }
  38857. }
  38858. };
  38859. CameraInputsManager.prototype.removeByType = function (inputType) {
  38860. for (var cam in this.attached) {
  38861. var input = this.attached[cam];
  38862. if (input.getClassName() === inputType) {
  38863. input.detachControl(this.attachedElement);
  38864. input.camera = null;
  38865. delete this.attached[cam];
  38866. this.rebuildInputCheck();
  38867. }
  38868. }
  38869. };
  38870. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  38871. var current = this.checkInputs;
  38872. return function () {
  38873. current();
  38874. fn();
  38875. };
  38876. };
  38877. CameraInputsManager.prototype.attachInput = function (input) {
  38878. if (this.attachedElement) {
  38879. input.attachControl(this.attachedElement, this.noPreventDefault);
  38880. }
  38881. };
  38882. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  38883. if (noPreventDefault === void 0) { noPreventDefault = false; }
  38884. if (this.attachedElement) {
  38885. return;
  38886. }
  38887. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  38888. this.attachedElement = element;
  38889. this.noPreventDefault = noPreventDefault;
  38890. for (var cam in this.attached) {
  38891. this.attached[cam].attachControl(element, noPreventDefault);
  38892. }
  38893. };
  38894. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  38895. if (disconnect === void 0) { disconnect = false; }
  38896. if (this.attachedElement !== element) {
  38897. return;
  38898. }
  38899. for (var cam in this.attached) {
  38900. this.attached[cam].detachControl(element);
  38901. if (disconnect) {
  38902. this.attached[cam].camera = null;
  38903. }
  38904. }
  38905. this.attachedElement = null;
  38906. };
  38907. CameraInputsManager.prototype.rebuildInputCheck = function () {
  38908. this.checkInputs = function () { };
  38909. for (var cam in this.attached) {
  38910. var input = this.attached[cam];
  38911. if (input.checkInputs) {
  38912. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38913. }
  38914. }
  38915. };
  38916. CameraInputsManager.prototype.clear = function () {
  38917. if (this.attachedElement) {
  38918. this.detachElement(this.attachedElement, true);
  38919. }
  38920. this.attached = {};
  38921. this.attachedElement = null;
  38922. this.checkInputs = function () { };
  38923. };
  38924. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  38925. var inputs = {};
  38926. for (var cam in this.attached) {
  38927. var input = this.attached[cam];
  38928. var res = BABYLON.SerializationHelper.Serialize(input);
  38929. inputs[input.getClassName()] = res;
  38930. }
  38931. serializedCamera.inputsmgr = inputs;
  38932. };
  38933. CameraInputsManager.prototype.parse = function (parsedCamera) {
  38934. var parsedInputs = parsedCamera.inputsmgr;
  38935. if (parsedInputs) {
  38936. this.clear();
  38937. for (var n in parsedInputs) {
  38938. var construct = BABYLON.CameraInputTypes[n];
  38939. if (construct) {
  38940. var parsedinput = parsedInputs[n];
  38941. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  38942. this.add(input);
  38943. }
  38944. }
  38945. }
  38946. else {
  38947. //2016-03-08 this part is for managing backward compatibility
  38948. for (var n in this.attached) {
  38949. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  38950. if (construct) {
  38951. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  38952. this.remove(this.attached[n]);
  38953. this.add(input);
  38954. }
  38955. }
  38956. }
  38957. };
  38958. return CameraInputsManager;
  38959. }());
  38960. BABYLON.CameraInputsManager = CameraInputsManager;
  38961. })(BABYLON || (BABYLON = {}));
  38962. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  38963. var BABYLON;
  38964. (function (BABYLON) {
  38965. var TargetCamera = /** @class */ (function (_super) {
  38966. __extends(TargetCamera, _super);
  38967. function TargetCamera(name, position, scene) {
  38968. var _this = _super.call(this, name, position, scene) || this;
  38969. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38970. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  38971. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  38972. _this.speed = 2.0;
  38973. _this.noRotationConstraint = false;
  38974. _this.lockedTarget = null;
  38975. _this._currentTarget = BABYLON.Vector3.Zero();
  38976. _this._viewMatrix = BABYLON.Matrix.Zero();
  38977. _this._camMatrix = BABYLON.Matrix.Zero();
  38978. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  38979. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  38980. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  38981. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  38982. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  38983. _this._lookAtTemp = BABYLON.Matrix.Zero();
  38984. _this._tempMatrix = BABYLON.Matrix.Zero();
  38985. return _this;
  38986. }
  38987. TargetCamera.prototype.getFrontPosition = function (distance) {
  38988. this.getWorldMatrix();
  38989. var direction = this.getTarget().subtract(this.position);
  38990. direction.normalize();
  38991. direction.scaleInPlace(distance);
  38992. return this.globalPosition.add(direction);
  38993. };
  38994. TargetCamera.prototype._getLockedTargetPosition = function () {
  38995. if (!this.lockedTarget) {
  38996. return null;
  38997. }
  38998. if (this.lockedTarget.absolutePosition) {
  38999. this.lockedTarget.computeWorldMatrix();
  39000. }
  39001. return this.lockedTarget.absolutePosition || this.lockedTarget;
  39002. };
  39003. TargetCamera.prototype.storeState = function () {
  39004. this._storedPosition = this.position.clone();
  39005. this._storedRotation = this.rotation.clone();
  39006. if (this.rotationQuaternion) {
  39007. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  39008. }
  39009. return _super.prototype.storeState.call(this);
  39010. };
  39011. /**
  39012. * Restored camera state. You must call storeState() first
  39013. */
  39014. TargetCamera.prototype._restoreStateValues = function () {
  39015. if (!_super.prototype._restoreStateValues.call(this)) {
  39016. return false;
  39017. }
  39018. this.position = this._storedPosition.clone();
  39019. this.rotation = this._storedRotation.clone();
  39020. if (this.rotationQuaternion) {
  39021. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  39022. }
  39023. this.cameraDirection.copyFromFloats(0, 0, 0);
  39024. this.cameraRotation.copyFromFloats(0, 0);
  39025. return true;
  39026. };
  39027. // Cache
  39028. TargetCamera.prototype._initCache = function () {
  39029. _super.prototype._initCache.call(this);
  39030. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39031. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39032. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39033. };
  39034. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  39035. if (!ignoreParentClass) {
  39036. _super.prototype._updateCache.call(this);
  39037. }
  39038. var lockedTargetPosition = this._getLockedTargetPosition();
  39039. if (!lockedTargetPosition) {
  39040. this._cache.lockedTarget = null;
  39041. }
  39042. else {
  39043. if (!this._cache.lockedTarget) {
  39044. this._cache.lockedTarget = lockedTargetPosition.clone();
  39045. }
  39046. else {
  39047. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  39048. }
  39049. }
  39050. this._cache.rotation.copyFrom(this.rotation);
  39051. if (this.rotationQuaternion)
  39052. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39053. };
  39054. // Synchronized
  39055. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  39056. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  39057. return false;
  39058. }
  39059. var lockedTargetPosition = this._getLockedTargetPosition();
  39060. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  39061. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  39062. };
  39063. // Methods
  39064. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  39065. var engine = this.getEngine();
  39066. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  39067. };
  39068. // Target
  39069. TargetCamera.prototype.setTarget = function (target) {
  39070. this.upVector.normalize();
  39071. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  39072. this._camMatrix.invert();
  39073. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  39074. var vDir = target.subtract(this.position);
  39075. if (vDir.x >= 0.0) {
  39076. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  39077. }
  39078. else {
  39079. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  39080. }
  39081. this.rotation.z = 0;
  39082. if (isNaN(this.rotation.x)) {
  39083. this.rotation.x = 0;
  39084. }
  39085. if (isNaN(this.rotation.y)) {
  39086. this.rotation.y = 0;
  39087. }
  39088. if (isNaN(this.rotation.z)) {
  39089. this.rotation.z = 0;
  39090. }
  39091. if (this.rotationQuaternion) {
  39092. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39093. }
  39094. };
  39095. /**
  39096. * Return the current target position of the camera. This value is expressed in local space.
  39097. */
  39098. TargetCamera.prototype.getTarget = function () {
  39099. return this._currentTarget;
  39100. };
  39101. TargetCamera.prototype._decideIfNeedsToMove = function () {
  39102. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39103. };
  39104. TargetCamera.prototype._updatePosition = function () {
  39105. if (this.parent) {
  39106. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  39107. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  39108. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  39109. return;
  39110. }
  39111. this.position.addInPlace(this.cameraDirection);
  39112. };
  39113. TargetCamera.prototype._checkInputs = function () {
  39114. var needToMove = this._decideIfNeedsToMove();
  39115. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  39116. // Move
  39117. if (needToMove) {
  39118. this._updatePosition();
  39119. }
  39120. // Rotate
  39121. if (needToRotate) {
  39122. this.rotation.x += this.cameraRotation.x;
  39123. this.rotation.y += this.cameraRotation.y;
  39124. //rotate, if quaternion is set and rotation was used
  39125. if (this.rotationQuaternion) {
  39126. var len = this.rotation.lengthSquared();
  39127. if (len) {
  39128. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39129. }
  39130. }
  39131. if (!this.noRotationConstraint) {
  39132. var limit = (Math.PI / 2) * 0.95;
  39133. if (this.rotation.x > limit)
  39134. this.rotation.x = limit;
  39135. if (this.rotation.x < -limit)
  39136. this.rotation.x = -limit;
  39137. }
  39138. }
  39139. // Inertia
  39140. if (needToMove) {
  39141. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  39142. this.cameraDirection.x = 0;
  39143. }
  39144. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  39145. this.cameraDirection.y = 0;
  39146. }
  39147. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  39148. this.cameraDirection.z = 0;
  39149. }
  39150. this.cameraDirection.scaleInPlace(this.inertia);
  39151. }
  39152. if (needToRotate) {
  39153. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  39154. this.cameraRotation.x = 0;
  39155. }
  39156. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  39157. this.cameraRotation.y = 0;
  39158. }
  39159. this.cameraRotation.scaleInPlace(this.inertia);
  39160. }
  39161. _super.prototype._checkInputs.call(this);
  39162. };
  39163. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  39164. if (this.rotationQuaternion) {
  39165. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  39166. }
  39167. else {
  39168. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  39169. }
  39170. //update the up vector!
  39171. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  39172. };
  39173. TargetCamera.prototype._getViewMatrix = function () {
  39174. if (this.lockedTarget) {
  39175. this.setTarget(this._getLockedTargetPosition());
  39176. }
  39177. // Compute
  39178. this._updateCameraRotationMatrix();
  39179. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  39180. // Computing target and final matrix
  39181. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  39182. if (this.getScene().useRightHandedSystem) {
  39183. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39184. }
  39185. else {
  39186. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39187. }
  39188. return this._viewMatrix;
  39189. };
  39190. /**
  39191. * @override
  39192. * Override Camera.createRigCamera
  39193. */
  39194. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39195. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  39196. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  39197. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  39198. if (!this.rotationQuaternion) {
  39199. this.rotationQuaternion = new BABYLON.Quaternion();
  39200. }
  39201. rigCamera._cameraRigParams = {};
  39202. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  39203. }
  39204. return rigCamera;
  39205. }
  39206. return null;
  39207. };
  39208. /**
  39209. * @override
  39210. * Override Camera._updateRigCameras
  39211. */
  39212. TargetCamera.prototype._updateRigCameras = function () {
  39213. var camLeft = this._rigCameras[0];
  39214. var camRight = this._rigCameras[1];
  39215. switch (this.cameraRigMode) {
  39216. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39217. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39218. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39219. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39220. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  39221. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  39222. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  39223. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  39224. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  39225. camLeft.setTarget(this.getTarget());
  39226. camRight.setTarget(this.getTarget());
  39227. break;
  39228. case BABYLON.Camera.RIG_MODE_VR:
  39229. if (camLeft.rotationQuaternion) {
  39230. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39231. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39232. }
  39233. else {
  39234. camLeft.rotation.copyFrom(this.rotation);
  39235. camRight.rotation.copyFrom(this.rotation);
  39236. }
  39237. camLeft.position.copyFrom(this.position);
  39238. camRight.position.copyFrom(this.position);
  39239. break;
  39240. }
  39241. _super.prototype._updateRigCameras.call(this);
  39242. };
  39243. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  39244. if (!this._rigCamTransformMatrix) {
  39245. this._rigCamTransformMatrix = new BABYLON.Matrix();
  39246. }
  39247. var target = this.getTarget();
  39248. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  39249. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  39250. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  39251. };
  39252. TargetCamera.prototype.getClassName = function () {
  39253. return "TargetCamera";
  39254. };
  39255. __decorate([
  39256. BABYLON.serializeAsVector3()
  39257. ], TargetCamera.prototype, "rotation", void 0);
  39258. __decorate([
  39259. BABYLON.serialize()
  39260. ], TargetCamera.prototype, "speed", void 0);
  39261. __decorate([
  39262. BABYLON.serializeAsMeshReference("lockedTargetId")
  39263. ], TargetCamera.prototype, "lockedTarget", void 0);
  39264. return TargetCamera;
  39265. }(BABYLON.Camera));
  39266. BABYLON.TargetCamera = TargetCamera;
  39267. })(BABYLON || (BABYLON = {}));
  39268. //# sourceMappingURL=babylon.targetCamera.js.map
  39269. var BABYLON;
  39270. (function (BABYLON) {
  39271. var FreeCameraMouseInput = /** @class */ (function () {
  39272. function FreeCameraMouseInput(touchEnabled) {
  39273. if (touchEnabled === void 0) { touchEnabled = true; }
  39274. this.touchEnabled = touchEnabled;
  39275. this.buttons = [0, 1, 2];
  39276. this.angularSensibility = 2000.0;
  39277. this.previousPosition = null;
  39278. }
  39279. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  39280. var _this = this;
  39281. var engine = this.camera.getEngine();
  39282. if (!this._pointerInput) {
  39283. this._pointerInput = function (p, s) {
  39284. var evt = p.event;
  39285. if (engine.isInVRExclusivePointerMode) {
  39286. return;
  39287. }
  39288. if (!_this.touchEnabled && evt.pointerType === "touch") {
  39289. return;
  39290. }
  39291. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39292. return;
  39293. }
  39294. var srcElement = (evt.srcElement || evt.target);
  39295. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  39296. try {
  39297. srcElement.setPointerCapture(evt.pointerId);
  39298. }
  39299. catch (e) {
  39300. //Nothing to do with the error. Execution will continue.
  39301. }
  39302. _this.previousPosition = {
  39303. x: evt.clientX,
  39304. y: evt.clientY
  39305. };
  39306. if (!noPreventDefault) {
  39307. evt.preventDefault();
  39308. element.focus();
  39309. }
  39310. }
  39311. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  39312. try {
  39313. srcElement.releasePointerCapture(evt.pointerId);
  39314. }
  39315. catch (e) {
  39316. //Nothing to do with the error.
  39317. }
  39318. _this.previousPosition = null;
  39319. if (!noPreventDefault) {
  39320. evt.preventDefault();
  39321. }
  39322. }
  39323. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39324. if (!_this.previousPosition || engine.isPointerLock) {
  39325. return;
  39326. }
  39327. var offsetX = evt.clientX - _this.previousPosition.x;
  39328. var offsetY = evt.clientY - _this.previousPosition.y;
  39329. if (_this.camera.getScene().useRightHandedSystem) {
  39330. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  39331. }
  39332. else {
  39333. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  39334. }
  39335. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  39336. _this.previousPosition = {
  39337. x: evt.clientX,
  39338. y: evt.clientY
  39339. };
  39340. if (!noPreventDefault) {
  39341. evt.preventDefault();
  39342. }
  39343. }
  39344. };
  39345. }
  39346. this._onMouseMove = function (evt) {
  39347. if (!engine.isPointerLock) {
  39348. return;
  39349. }
  39350. if (engine.isInVRExclusivePointerMode) {
  39351. return;
  39352. }
  39353. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  39354. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  39355. if (_this.camera.getScene().useRightHandedSystem) {
  39356. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  39357. }
  39358. else {
  39359. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  39360. }
  39361. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  39362. _this.previousPosition = null;
  39363. if (!noPreventDefault) {
  39364. evt.preventDefault();
  39365. }
  39366. };
  39367. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  39368. element.addEventListener("mousemove", this._onMouseMove, false);
  39369. };
  39370. FreeCameraMouseInput.prototype.detachControl = function (element) {
  39371. if (this._observer && element) {
  39372. this.camera.getScene().onPointerObservable.remove(this._observer);
  39373. if (this._onMouseMove) {
  39374. element.removeEventListener("mousemove", this._onMouseMove);
  39375. }
  39376. this._observer = null;
  39377. this._onMouseMove = null;
  39378. this.previousPosition = null;
  39379. }
  39380. };
  39381. FreeCameraMouseInput.prototype.getClassName = function () {
  39382. return "FreeCameraMouseInput";
  39383. };
  39384. FreeCameraMouseInput.prototype.getSimpleName = function () {
  39385. return "mouse";
  39386. };
  39387. __decorate([
  39388. BABYLON.serialize()
  39389. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  39390. __decorate([
  39391. BABYLON.serialize()
  39392. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  39393. return FreeCameraMouseInput;
  39394. }());
  39395. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  39396. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  39397. })(BABYLON || (BABYLON = {}));
  39398. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  39399. var BABYLON;
  39400. (function (BABYLON) {
  39401. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  39402. function FreeCameraKeyboardMoveInput() {
  39403. this._keys = new Array();
  39404. this.keysUp = [38];
  39405. this.keysDown = [40];
  39406. this.keysLeft = [37];
  39407. this.keysRight = [39];
  39408. }
  39409. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39410. var _this = this;
  39411. if (this._onCanvasBlurObserver) {
  39412. return;
  39413. }
  39414. this._scene = this.camera.getScene();
  39415. this._engine = this._scene.getEngine();
  39416. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39417. _this._keys = [];
  39418. });
  39419. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39420. var evt = info.event;
  39421. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39422. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39423. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39424. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39425. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  39426. var index = _this._keys.indexOf(evt.keyCode);
  39427. if (index === -1) {
  39428. _this._keys.push(evt.keyCode);
  39429. }
  39430. if (!noPreventDefault) {
  39431. evt.preventDefault();
  39432. }
  39433. }
  39434. }
  39435. else {
  39436. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39437. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39438. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39439. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  39440. var index = _this._keys.indexOf(evt.keyCode);
  39441. if (index >= 0) {
  39442. _this._keys.splice(index, 1);
  39443. }
  39444. if (!noPreventDefault) {
  39445. evt.preventDefault();
  39446. }
  39447. }
  39448. }
  39449. });
  39450. };
  39451. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39452. if (this._scene) {
  39453. if (this._onKeyboardObserver) {
  39454. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39455. }
  39456. if (this._onCanvasBlurObserver) {
  39457. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39458. }
  39459. this._onKeyboardObserver = null;
  39460. this._onCanvasBlurObserver = null;
  39461. }
  39462. this._keys = [];
  39463. };
  39464. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39465. if (this._onKeyboardObserver) {
  39466. var camera = this.camera;
  39467. // Keyboard
  39468. for (var index = 0; index < this._keys.length; index++) {
  39469. var keyCode = this._keys[index];
  39470. var speed = camera._computeLocalCameraSpeed();
  39471. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39472. camera._localDirection.copyFromFloats(-speed, 0, 0);
  39473. }
  39474. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39475. camera._localDirection.copyFromFloats(0, 0, speed);
  39476. }
  39477. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39478. camera._localDirection.copyFromFloats(speed, 0, 0);
  39479. }
  39480. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39481. camera._localDirection.copyFromFloats(0, 0, -speed);
  39482. }
  39483. if (camera.getScene().useRightHandedSystem) {
  39484. camera._localDirection.z *= -1;
  39485. }
  39486. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  39487. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  39488. camera.cameraDirection.addInPlace(camera._transformedDirection);
  39489. }
  39490. }
  39491. };
  39492. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  39493. return "FreeCameraKeyboardMoveInput";
  39494. };
  39495. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  39496. this._keys = [];
  39497. };
  39498. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39499. return "keyboard";
  39500. };
  39501. __decorate([
  39502. BABYLON.serialize()
  39503. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39504. __decorate([
  39505. BABYLON.serialize()
  39506. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39507. __decorate([
  39508. BABYLON.serialize()
  39509. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39510. __decorate([
  39511. BABYLON.serialize()
  39512. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39513. return FreeCameraKeyboardMoveInput;
  39514. }());
  39515. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  39516. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  39517. })(BABYLON || (BABYLON = {}));
  39518. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  39519. var BABYLON;
  39520. (function (BABYLON) {
  39521. var FreeCameraInputsManager = /** @class */ (function (_super) {
  39522. __extends(FreeCameraInputsManager, _super);
  39523. function FreeCameraInputsManager(camera) {
  39524. return _super.call(this, camera) || this;
  39525. }
  39526. FreeCameraInputsManager.prototype.addKeyboard = function () {
  39527. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  39528. return this;
  39529. };
  39530. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  39531. if (touchEnabled === void 0) { touchEnabled = true; }
  39532. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  39533. return this;
  39534. };
  39535. FreeCameraInputsManager.prototype.addGamepad = function () {
  39536. this.add(new BABYLON.FreeCameraGamepadInput());
  39537. return this;
  39538. };
  39539. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  39540. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  39541. return this;
  39542. };
  39543. FreeCameraInputsManager.prototype.addTouch = function () {
  39544. this.add(new BABYLON.FreeCameraTouchInput());
  39545. return this;
  39546. };
  39547. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  39548. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  39549. return this;
  39550. };
  39551. return FreeCameraInputsManager;
  39552. }(BABYLON.CameraInputsManager));
  39553. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  39554. })(BABYLON || (BABYLON = {}));
  39555. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  39556. var BABYLON;
  39557. (function (BABYLON) {
  39558. var FreeCamera = /** @class */ (function (_super) {
  39559. __extends(FreeCamera, _super);
  39560. function FreeCamera(name, position, scene) {
  39561. var _this = _super.call(this, name, position, scene) || this;
  39562. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  39563. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  39564. _this.checkCollisions = false;
  39565. _this.applyGravity = false;
  39566. _this._needMoveForGravity = false;
  39567. _this._oldPosition = BABYLON.Vector3.Zero();
  39568. _this._diffPosition = BABYLON.Vector3.Zero();
  39569. _this._newPosition = BABYLON.Vector3.Zero();
  39570. // Collisions
  39571. _this._collisionMask = -1;
  39572. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39573. if (collidedMesh === void 0) { collidedMesh = null; }
  39574. //TODO move this to the collision coordinator!
  39575. if (_this.getScene().workerCollisions)
  39576. newPosition.multiplyInPlace(_this._collider._radius);
  39577. var updatePosition = function (newPos) {
  39578. _this._newPosition.copyFrom(newPos);
  39579. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  39580. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  39581. _this.position.addInPlace(_this._diffPosition);
  39582. if (_this.onCollide && collidedMesh) {
  39583. _this.onCollide(collidedMesh);
  39584. }
  39585. }
  39586. };
  39587. updatePosition(newPosition);
  39588. };
  39589. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  39590. _this.inputs.addKeyboard().addMouse();
  39591. return _this;
  39592. }
  39593. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  39594. //-- begin properties for backward compatibility for inputs
  39595. get: function () {
  39596. var mouse = this.inputs.attached["mouse"];
  39597. if (mouse)
  39598. return mouse.angularSensibility;
  39599. return 0;
  39600. },
  39601. set: function (value) {
  39602. var mouse = this.inputs.attached["mouse"];
  39603. if (mouse)
  39604. mouse.angularSensibility = value;
  39605. },
  39606. enumerable: true,
  39607. configurable: true
  39608. });
  39609. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  39610. get: function () {
  39611. var keyboard = this.inputs.attached["keyboard"];
  39612. if (keyboard)
  39613. return keyboard.keysUp;
  39614. return [];
  39615. },
  39616. set: function (value) {
  39617. var keyboard = this.inputs.attached["keyboard"];
  39618. if (keyboard)
  39619. keyboard.keysUp = value;
  39620. },
  39621. enumerable: true,
  39622. configurable: true
  39623. });
  39624. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  39625. get: function () {
  39626. var keyboard = this.inputs.attached["keyboard"];
  39627. if (keyboard)
  39628. return keyboard.keysDown;
  39629. return [];
  39630. },
  39631. set: function (value) {
  39632. var keyboard = this.inputs.attached["keyboard"];
  39633. if (keyboard)
  39634. keyboard.keysDown = value;
  39635. },
  39636. enumerable: true,
  39637. configurable: true
  39638. });
  39639. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  39640. get: function () {
  39641. var keyboard = this.inputs.attached["keyboard"];
  39642. if (keyboard)
  39643. return keyboard.keysLeft;
  39644. return [];
  39645. },
  39646. set: function (value) {
  39647. var keyboard = this.inputs.attached["keyboard"];
  39648. if (keyboard)
  39649. keyboard.keysLeft = value;
  39650. },
  39651. enumerable: true,
  39652. configurable: true
  39653. });
  39654. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  39655. get: function () {
  39656. var keyboard = this.inputs.attached["keyboard"];
  39657. if (keyboard)
  39658. return keyboard.keysRight;
  39659. return [];
  39660. },
  39661. set: function (value) {
  39662. var keyboard = this.inputs.attached["keyboard"];
  39663. if (keyboard)
  39664. keyboard.keysRight = value;
  39665. },
  39666. enumerable: true,
  39667. configurable: true
  39668. });
  39669. // Controls
  39670. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  39671. this.inputs.attachElement(element, noPreventDefault);
  39672. };
  39673. FreeCamera.prototype.detachControl = function (element) {
  39674. this.inputs.detachElement(element);
  39675. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  39676. this.cameraRotation = new BABYLON.Vector2(0, 0);
  39677. };
  39678. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  39679. get: function () {
  39680. return this._collisionMask;
  39681. },
  39682. set: function (mask) {
  39683. this._collisionMask = !isNaN(mask) ? mask : -1;
  39684. },
  39685. enumerable: true,
  39686. configurable: true
  39687. });
  39688. FreeCamera.prototype._collideWithWorld = function (displacement) {
  39689. var globalPosition;
  39690. if (this.parent) {
  39691. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  39692. }
  39693. else {
  39694. globalPosition = this.position;
  39695. }
  39696. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  39697. this._oldPosition.addInPlace(this.ellipsoidOffset);
  39698. if (!this._collider) {
  39699. this._collider = new BABYLON.Collider();
  39700. }
  39701. this._collider._radius = this.ellipsoid;
  39702. this._collider.collisionMask = this._collisionMask;
  39703. //no need for clone, as long as gravity is not on.
  39704. var actualDisplacement = displacement;
  39705. //add gravity to the direction to prevent the dual-collision checking
  39706. if (this.applyGravity) {
  39707. //this prevents mending with cameraDirection, a global variable of the free camera class.
  39708. actualDisplacement = displacement.add(this.getScene().gravity);
  39709. }
  39710. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39711. };
  39712. FreeCamera.prototype._checkInputs = function () {
  39713. if (!this._localDirection) {
  39714. this._localDirection = BABYLON.Vector3.Zero();
  39715. this._transformedDirection = BABYLON.Vector3.Zero();
  39716. }
  39717. this.inputs.checkInputs();
  39718. _super.prototype._checkInputs.call(this);
  39719. };
  39720. FreeCamera.prototype._decideIfNeedsToMove = function () {
  39721. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39722. };
  39723. FreeCamera.prototype._updatePosition = function () {
  39724. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  39725. this._collideWithWorld(this.cameraDirection);
  39726. }
  39727. else {
  39728. _super.prototype._updatePosition.call(this);
  39729. }
  39730. };
  39731. FreeCamera.prototype.dispose = function () {
  39732. this.inputs.clear();
  39733. _super.prototype.dispose.call(this);
  39734. };
  39735. FreeCamera.prototype.getClassName = function () {
  39736. return "FreeCamera";
  39737. };
  39738. __decorate([
  39739. BABYLON.serializeAsVector3()
  39740. ], FreeCamera.prototype, "ellipsoid", void 0);
  39741. __decorate([
  39742. BABYLON.serializeAsVector3()
  39743. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  39744. __decorate([
  39745. BABYLON.serialize()
  39746. ], FreeCamera.prototype, "checkCollisions", void 0);
  39747. __decorate([
  39748. BABYLON.serialize()
  39749. ], FreeCamera.prototype, "applyGravity", void 0);
  39750. return FreeCamera;
  39751. }(BABYLON.TargetCamera));
  39752. BABYLON.FreeCamera = FreeCamera;
  39753. })(BABYLON || (BABYLON = {}));
  39754. //# sourceMappingURL=babylon.freeCamera.js.map
  39755. var BABYLON;
  39756. (function (BABYLON) {
  39757. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  39758. function ArcRotateCameraKeyboardMoveInput() {
  39759. this._keys = new Array();
  39760. this.keysUp = [38];
  39761. this.keysDown = [40];
  39762. this.keysLeft = [37];
  39763. this.keysRight = [39];
  39764. this.keysReset = [220];
  39765. this.panningSensibility = 50.0;
  39766. this.zoomingSensibility = 25.0;
  39767. this.useAltToZoom = true;
  39768. }
  39769. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39770. var _this = this;
  39771. if (this._onCanvasBlurObserver) {
  39772. return;
  39773. }
  39774. this._scene = this.camera.getScene();
  39775. this._engine = this._scene.getEngine();
  39776. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39777. _this._keys = [];
  39778. });
  39779. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39780. var evt = info.event;
  39781. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39782. _this._ctrlPressed = evt.ctrlKey;
  39783. _this._altPressed = evt.altKey;
  39784. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39785. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39786. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39787. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39788. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39789. var index = _this._keys.indexOf(evt.keyCode);
  39790. if (index === -1) {
  39791. _this._keys.push(evt.keyCode);
  39792. }
  39793. if (evt.preventDefault) {
  39794. if (!noPreventDefault) {
  39795. evt.preventDefault();
  39796. }
  39797. }
  39798. }
  39799. }
  39800. else {
  39801. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39802. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39803. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39804. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39805. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39806. var index = _this._keys.indexOf(evt.keyCode);
  39807. if (index >= 0) {
  39808. _this._keys.splice(index, 1);
  39809. }
  39810. if (evt.preventDefault) {
  39811. if (!noPreventDefault) {
  39812. evt.preventDefault();
  39813. }
  39814. }
  39815. }
  39816. }
  39817. });
  39818. };
  39819. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39820. if (this._scene) {
  39821. if (this._onKeyboardObserver) {
  39822. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39823. }
  39824. if (this._onCanvasBlurObserver) {
  39825. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39826. }
  39827. this._onKeyboardObserver = null;
  39828. this._onCanvasBlurObserver = null;
  39829. }
  39830. this._keys = [];
  39831. };
  39832. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39833. if (this._onKeyboardObserver) {
  39834. var camera = this.camera;
  39835. for (var index = 0; index < this._keys.length; index++) {
  39836. var keyCode = this._keys[index];
  39837. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39838. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39839. camera.inertialPanningX -= 1 / this.panningSensibility;
  39840. }
  39841. else {
  39842. camera.inertialAlphaOffset -= 0.01;
  39843. }
  39844. }
  39845. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39846. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39847. camera.inertialPanningY += 1 / this.panningSensibility;
  39848. }
  39849. else if (this._altPressed && this.useAltToZoom) {
  39850. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  39851. }
  39852. else {
  39853. camera.inertialBetaOffset -= 0.01;
  39854. }
  39855. }
  39856. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39857. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39858. camera.inertialPanningX += 1 / this.panningSensibility;
  39859. }
  39860. else {
  39861. camera.inertialAlphaOffset += 0.01;
  39862. }
  39863. }
  39864. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39865. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39866. camera.inertialPanningY -= 1 / this.panningSensibility;
  39867. }
  39868. else if (this._altPressed && this.useAltToZoom) {
  39869. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  39870. }
  39871. else {
  39872. camera.inertialBetaOffset += 0.01;
  39873. }
  39874. }
  39875. else if (this.keysReset.indexOf(keyCode) !== -1) {
  39876. camera.restoreState();
  39877. }
  39878. }
  39879. }
  39880. };
  39881. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  39882. return "ArcRotateCameraKeyboardMoveInput";
  39883. };
  39884. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39885. return "keyboard";
  39886. };
  39887. __decorate([
  39888. BABYLON.serialize()
  39889. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39890. __decorate([
  39891. BABYLON.serialize()
  39892. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39893. __decorate([
  39894. BABYLON.serialize()
  39895. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39896. __decorate([
  39897. BABYLON.serialize()
  39898. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39899. __decorate([
  39900. BABYLON.serialize()
  39901. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  39902. __decorate([
  39903. BABYLON.serialize()
  39904. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  39905. __decorate([
  39906. BABYLON.serialize()
  39907. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  39908. __decorate([
  39909. BABYLON.serialize()
  39910. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  39911. return ArcRotateCameraKeyboardMoveInput;
  39912. }());
  39913. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  39914. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  39915. })(BABYLON || (BABYLON = {}));
  39916. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  39917. var BABYLON;
  39918. (function (BABYLON) {
  39919. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  39920. function ArcRotateCameraMouseWheelInput() {
  39921. this.wheelPrecision = 3.0;
  39922. /**
  39923. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  39924. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  39925. */
  39926. this.wheelDeltaPercentage = 0;
  39927. }
  39928. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  39929. var _this = this;
  39930. this._wheel = function (p, s) {
  39931. //sanity check - this should be a PointerWheel event.
  39932. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  39933. return;
  39934. var event = p.event;
  39935. var delta = 0;
  39936. if (event.wheelDelta) {
  39937. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  39938. }
  39939. else if (event.detail) {
  39940. delta = -event.detail / _this.wheelPrecision;
  39941. }
  39942. if (delta)
  39943. _this.camera.inertialRadiusOffset += delta;
  39944. if (event.preventDefault) {
  39945. if (!noPreventDefault) {
  39946. event.preventDefault();
  39947. }
  39948. }
  39949. };
  39950. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  39951. };
  39952. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  39953. if (this._observer && element) {
  39954. this.camera.getScene().onPointerObservable.remove(this._observer);
  39955. this._observer = null;
  39956. this._wheel = null;
  39957. }
  39958. };
  39959. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  39960. return "ArcRotateCameraMouseWheelInput";
  39961. };
  39962. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  39963. return "mousewheel";
  39964. };
  39965. __decorate([
  39966. BABYLON.serialize()
  39967. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  39968. __decorate([
  39969. BABYLON.serialize()
  39970. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  39971. return ArcRotateCameraMouseWheelInput;
  39972. }());
  39973. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  39974. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  39975. })(BABYLON || (BABYLON = {}));
  39976. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  39977. var BABYLON;
  39978. (function (BABYLON) {
  39979. var ArcRotateCameraPointersInput = /** @class */ (function () {
  39980. function ArcRotateCameraPointersInput() {
  39981. this.buttons = [0, 1, 2];
  39982. this.angularSensibilityX = 1000.0;
  39983. this.angularSensibilityY = 1000.0;
  39984. this.pinchPrecision = 12.0;
  39985. /**
  39986. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  39987. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  39988. */
  39989. this.pinchDeltaPercentage = 0;
  39990. this.panningSensibility = 1000.0;
  39991. this.multiTouchPanning = true;
  39992. this.multiTouchPanAndZoom = true;
  39993. this._isPanClick = false;
  39994. this.pinchInwards = true;
  39995. }
  39996. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  39997. var _this = this;
  39998. var engine = this.camera.getEngine();
  39999. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  40000. var pointA = null;
  40001. var pointB = null;
  40002. var previousPinchSquaredDistance = 0;
  40003. var initialDistance = 0;
  40004. var twoFingerActivityCount = 0;
  40005. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  40006. this._pointerInput = function (p, s) {
  40007. var evt = p.event;
  40008. var isTouch = p.event.pointerType === "touch";
  40009. if (engine.isInVRExclusivePointerMode) {
  40010. return;
  40011. }
  40012. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  40013. return;
  40014. }
  40015. var srcElement = (evt.srcElement || evt.target);
  40016. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  40017. try {
  40018. srcElement.setPointerCapture(evt.pointerId);
  40019. }
  40020. catch (e) {
  40021. //Nothing to do with the error. Execution will continue.
  40022. }
  40023. // Manage panning with pan button click
  40024. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  40025. // manage pointers
  40026. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  40027. if (pointA === null) {
  40028. pointA = cacheSoloPointer;
  40029. }
  40030. else if (pointB === null) {
  40031. pointB = cacheSoloPointer;
  40032. }
  40033. if (!noPreventDefault) {
  40034. evt.preventDefault();
  40035. element.focus();
  40036. }
  40037. }
  40038. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  40039. _this.camera.restoreState();
  40040. }
  40041. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  40042. try {
  40043. srcElement.releasePointerCapture(evt.pointerId);
  40044. }
  40045. catch (e) {
  40046. //Nothing to do with the error.
  40047. }
  40048. cacheSoloPointer = null;
  40049. previousPinchSquaredDistance = 0;
  40050. previousMultiTouchPanPosition.isPaning = false;
  40051. previousMultiTouchPanPosition.isPinching = false;
  40052. twoFingerActivityCount = 0;
  40053. initialDistance = 0;
  40054. if (!isTouch) {
  40055. pointB = null; // Mouse and pen are mono pointer
  40056. }
  40057. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  40058. //but emptying completly pointers collection is required to fix a bug on iPhone :
  40059. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  40060. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  40061. if (engine.badOS) {
  40062. pointA = pointB = null;
  40063. }
  40064. else {
  40065. //only remove the impacted pointer in case of multitouch allowing on most
  40066. //platforms switching from rotate to zoom and pan seamlessly.
  40067. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  40068. pointA = pointB;
  40069. pointB = null;
  40070. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  40071. }
  40072. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  40073. pointB = null;
  40074. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  40075. }
  40076. else {
  40077. pointA = pointB = null;
  40078. }
  40079. }
  40080. if (!noPreventDefault) {
  40081. evt.preventDefault();
  40082. }
  40083. }
  40084. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  40085. if (!noPreventDefault) {
  40086. evt.preventDefault();
  40087. }
  40088. // One button down
  40089. if (pointA && pointB === null && cacheSoloPointer) {
  40090. if (_this.panningSensibility !== 0 &&
  40091. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  40092. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  40093. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  40094. }
  40095. else {
  40096. var offsetX = evt.clientX - cacheSoloPointer.x;
  40097. var offsetY = evt.clientY - cacheSoloPointer.y;
  40098. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  40099. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  40100. }
  40101. cacheSoloPointer.x = evt.clientX;
  40102. cacheSoloPointer.y = evt.clientY;
  40103. }
  40104. else if (pointA && pointB) {
  40105. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  40106. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  40107. ed.x = evt.clientX;
  40108. ed.y = evt.clientY;
  40109. var direction = _this.pinchInwards ? 1 : -1;
  40110. var distX = pointA.x - pointB.x;
  40111. var distY = pointA.y - pointB.y;
  40112. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  40113. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  40114. if (previousPinchSquaredDistance === 0) {
  40115. initialDistance = pinchDistance;
  40116. previousPinchSquaredDistance = pinchSquaredDistance;
  40117. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  40118. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  40119. return;
  40120. }
  40121. if (_this.multiTouchPanAndZoom) {
  40122. if (_this.pinchDeltaPercentage) {
  40123. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  40124. }
  40125. else {
  40126. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  40127. (_this.pinchPrecision *
  40128. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  40129. direction);
  40130. }
  40131. if (_this.panningSensibility !== 0) {
  40132. var pointersCenterX = (pointA.x + pointB.x) / 2;
  40133. var pointersCenterY = (pointA.y + pointB.y) / 2;
  40134. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  40135. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  40136. previousMultiTouchPanPosition.x = pointersCenterX;
  40137. previousMultiTouchPanPosition.y = pointersCenterY;
  40138. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  40139. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  40140. }
  40141. }
  40142. else {
  40143. twoFingerActivityCount++;
  40144. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  40145. if (_this.pinchDeltaPercentage) {
  40146. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  40147. }
  40148. else {
  40149. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  40150. (_this.pinchPrecision *
  40151. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  40152. direction);
  40153. }
  40154. previousMultiTouchPanPosition.isPaning = false;
  40155. previousMultiTouchPanPosition.isPinching = true;
  40156. }
  40157. else {
  40158. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  40159. if (!previousMultiTouchPanPosition.isPaning) {
  40160. previousMultiTouchPanPosition.isPaning = true;
  40161. previousMultiTouchPanPosition.isPinching = false;
  40162. previousMultiTouchPanPosition.x = ed.x;
  40163. previousMultiTouchPanPosition.y = ed.y;
  40164. return;
  40165. }
  40166. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  40167. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  40168. }
  40169. }
  40170. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  40171. previousMultiTouchPanPosition.x = ed.x;
  40172. previousMultiTouchPanPosition.y = ed.y;
  40173. }
  40174. }
  40175. previousPinchSquaredDistance = pinchSquaredDistance;
  40176. }
  40177. }
  40178. };
  40179. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  40180. this._onContextMenu = function (evt) {
  40181. evt.preventDefault();
  40182. };
  40183. if (!this.camera._useCtrlForPanning) {
  40184. element.addEventListener("contextmenu", this._onContextMenu, false);
  40185. }
  40186. this._onLostFocus = function () {
  40187. //this._keys = [];
  40188. pointA = pointB = null;
  40189. previousPinchSquaredDistance = 0;
  40190. previousMultiTouchPanPosition.isPaning = false;
  40191. previousMultiTouchPanPosition.isPinching = false;
  40192. twoFingerActivityCount = 0;
  40193. cacheSoloPointer = null;
  40194. initialDistance = 0;
  40195. };
  40196. this._onMouseMove = function (evt) {
  40197. if (!engine.isPointerLock) {
  40198. return;
  40199. }
  40200. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  40201. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  40202. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  40203. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  40204. if (!noPreventDefault) {
  40205. evt.preventDefault();
  40206. }
  40207. };
  40208. this._onGestureStart = function (e) {
  40209. if (window.MSGesture === undefined) {
  40210. return;
  40211. }
  40212. if (!_this._MSGestureHandler) {
  40213. _this._MSGestureHandler = new MSGesture();
  40214. _this._MSGestureHandler.target = element;
  40215. }
  40216. _this._MSGestureHandler.addPointer(e.pointerId);
  40217. };
  40218. this._onGesture = function (e) {
  40219. _this.camera.radius *= e.scale;
  40220. if (e.preventDefault) {
  40221. if (!noPreventDefault) {
  40222. e.stopPropagation();
  40223. e.preventDefault();
  40224. }
  40225. }
  40226. };
  40227. element.addEventListener("mousemove", this._onMouseMove, false);
  40228. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  40229. element.addEventListener("MSGestureChange", this._onGesture, false);
  40230. BABYLON.Tools.RegisterTopRootEvents([
  40231. { name: "blur", handler: this._onLostFocus }
  40232. ]);
  40233. };
  40234. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  40235. if (this._onLostFocus) {
  40236. BABYLON.Tools.UnregisterTopRootEvents([
  40237. { name: "blur", handler: this._onLostFocus }
  40238. ]);
  40239. }
  40240. if (element && this._observer) {
  40241. this.camera.getScene().onPointerObservable.remove(this._observer);
  40242. this._observer = null;
  40243. if (this._onContextMenu) {
  40244. element.removeEventListener("contextmenu", this._onContextMenu);
  40245. }
  40246. if (this._onMouseMove) {
  40247. element.removeEventListener("mousemove", this._onMouseMove);
  40248. }
  40249. if (this._onGestureStart) {
  40250. element.removeEventListener("MSPointerDown", this._onGestureStart);
  40251. }
  40252. if (this._onGesture) {
  40253. element.removeEventListener("MSGestureChange", this._onGesture);
  40254. }
  40255. this._isPanClick = false;
  40256. this.pinchInwards = true;
  40257. this._onMouseMove = null;
  40258. this._onGestureStart = null;
  40259. this._onGesture = null;
  40260. this._MSGestureHandler = null;
  40261. this._onLostFocus = null;
  40262. this._onContextMenu = null;
  40263. }
  40264. };
  40265. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  40266. return "ArcRotateCameraPointersInput";
  40267. };
  40268. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  40269. return "pointers";
  40270. };
  40271. __decorate([
  40272. BABYLON.serialize()
  40273. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  40274. __decorate([
  40275. BABYLON.serialize()
  40276. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  40277. __decorate([
  40278. BABYLON.serialize()
  40279. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  40280. __decorate([
  40281. BABYLON.serialize()
  40282. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  40283. __decorate([
  40284. BABYLON.serialize()
  40285. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  40286. __decorate([
  40287. BABYLON.serialize()
  40288. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  40289. __decorate([
  40290. BABYLON.serialize()
  40291. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  40292. __decorate([
  40293. BABYLON.serialize()
  40294. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  40295. return ArcRotateCameraPointersInput;
  40296. }());
  40297. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  40298. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  40299. })(BABYLON || (BABYLON = {}));
  40300. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  40301. var BABYLON;
  40302. (function (BABYLON) {
  40303. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  40304. __extends(ArcRotateCameraInputsManager, _super);
  40305. function ArcRotateCameraInputsManager(camera) {
  40306. return _super.call(this, camera) || this;
  40307. }
  40308. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  40309. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  40310. return this;
  40311. };
  40312. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  40313. this.add(new BABYLON.ArcRotateCameraPointersInput());
  40314. return this;
  40315. };
  40316. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  40317. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  40318. return this;
  40319. };
  40320. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  40321. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  40322. return this;
  40323. };
  40324. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  40325. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  40326. return this;
  40327. };
  40328. return ArcRotateCameraInputsManager;
  40329. }(BABYLON.CameraInputsManager));
  40330. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  40331. })(BABYLON || (BABYLON = {}));
  40332. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  40333. var BABYLON;
  40334. (function (BABYLON) {
  40335. var ArcRotateCamera = /** @class */ (function (_super) {
  40336. __extends(ArcRotateCamera, _super);
  40337. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  40338. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  40339. _this.inertialAlphaOffset = 0;
  40340. _this.inertialBetaOffset = 0;
  40341. _this.inertialRadiusOffset = 0;
  40342. _this.lowerAlphaLimit = null;
  40343. _this.upperAlphaLimit = null;
  40344. _this.lowerBetaLimit = 0.01;
  40345. _this.upperBetaLimit = Math.PI;
  40346. _this.lowerRadiusLimit = null;
  40347. _this.upperRadiusLimit = null;
  40348. _this.inertialPanningX = 0;
  40349. _this.inertialPanningY = 0;
  40350. _this.pinchToPanMaxDistance = 20;
  40351. _this.panningDistanceLimit = null;
  40352. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  40353. _this.panningInertia = 0.9;
  40354. //-- end properties for backward compatibility for inputs
  40355. _this.zoomOnFactor = 1;
  40356. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  40357. _this.allowUpsideDown = true;
  40358. _this._viewMatrix = new BABYLON.Matrix();
  40359. // Panning
  40360. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  40361. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  40362. _this.checkCollisions = false;
  40363. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  40364. _this._previousPosition = BABYLON.Vector3.Zero();
  40365. _this._collisionVelocity = BABYLON.Vector3.Zero();
  40366. _this._newPosition = BABYLON.Vector3.Zero();
  40367. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  40368. if (collidedMesh === void 0) { collidedMesh = null; }
  40369. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  40370. newPosition.multiplyInPlace(_this._collider._radius);
  40371. }
  40372. if (!collidedMesh) {
  40373. _this._previousPosition.copyFrom(_this.position);
  40374. }
  40375. else {
  40376. _this.setPosition(newPosition);
  40377. if (_this.onCollide) {
  40378. _this.onCollide(collidedMesh);
  40379. }
  40380. }
  40381. // Recompute because of constraints
  40382. var cosa = Math.cos(_this.alpha);
  40383. var sina = Math.sin(_this.alpha);
  40384. var cosb = Math.cos(_this.beta);
  40385. var sinb = Math.sin(_this.beta);
  40386. if (sinb === 0) {
  40387. sinb = 0.0001;
  40388. }
  40389. var target = _this._getTargetPosition();
  40390. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  40391. _this.position.copyFrom(_this._newPosition);
  40392. var up = _this.upVector;
  40393. if (_this.allowUpsideDown && _this.beta < 0) {
  40394. up = up.clone();
  40395. up = up.negate();
  40396. }
  40397. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  40398. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  40399. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  40400. _this._collisionTriggered = false;
  40401. };
  40402. _this._target = BABYLON.Vector3.Zero();
  40403. if (target) {
  40404. _this.setTarget(target);
  40405. }
  40406. _this.alpha = alpha;
  40407. _this.beta = beta;
  40408. _this.radius = radius;
  40409. _this.getViewMatrix();
  40410. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  40411. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  40412. return _this;
  40413. }
  40414. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  40415. get: function () {
  40416. return this._target;
  40417. },
  40418. set: function (value) {
  40419. this.setTarget(value);
  40420. },
  40421. enumerable: true,
  40422. configurable: true
  40423. });
  40424. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  40425. //-- begin properties for backward compatibility for inputs
  40426. get: function () {
  40427. var pointers = this.inputs.attached["pointers"];
  40428. if (pointers)
  40429. return pointers.angularSensibilityX;
  40430. return 0;
  40431. },
  40432. set: function (value) {
  40433. var pointers = this.inputs.attached["pointers"];
  40434. if (pointers) {
  40435. pointers.angularSensibilityX = value;
  40436. }
  40437. },
  40438. enumerable: true,
  40439. configurable: true
  40440. });
  40441. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  40442. get: function () {
  40443. var pointers = this.inputs.attached["pointers"];
  40444. if (pointers)
  40445. return pointers.angularSensibilityY;
  40446. return 0;
  40447. },
  40448. set: function (value) {
  40449. var pointers = this.inputs.attached["pointers"];
  40450. if (pointers) {
  40451. pointers.angularSensibilityY = value;
  40452. }
  40453. },
  40454. enumerable: true,
  40455. configurable: true
  40456. });
  40457. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  40458. get: function () {
  40459. var pointers = this.inputs.attached["pointers"];
  40460. if (pointers)
  40461. return pointers.pinchPrecision;
  40462. return 0;
  40463. },
  40464. set: function (value) {
  40465. var pointers = this.inputs.attached["pointers"];
  40466. if (pointers) {
  40467. pointers.pinchPrecision = value;
  40468. }
  40469. },
  40470. enumerable: true,
  40471. configurable: true
  40472. });
  40473. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  40474. get: function () {
  40475. var pointers = this.inputs.attached["pointers"];
  40476. if (pointers)
  40477. return pointers.pinchDeltaPercentage;
  40478. return 0;
  40479. },
  40480. set: function (value) {
  40481. var pointers = this.inputs.attached["pointers"];
  40482. if (pointers) {
  40483. pointers.pinchDeltaPercentage = value;
  40484. }
  40485. },
  40486. enumerable: true,
  40487. configurable: true
  40488. });
  40489. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  40490. get: function () {
  40491. var pointers = this.inputs.attached["pointers"];
  40492. if (pointers)
  40493. return pointers.panningSensibility;
  40494. return 0;
  40495. },
  40496. set: function (value) {
  40497. var pointers = this.inputs.attached["pointers"];
  40498. if (pointers) {
  40499. pointers.panningSensibility = value;
  40500. }
  40501. },
  40502. enumerable: true,
  40503. configurable: true
  40504. });
  40505. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  40506. get: function () {
  40507. var keyboard = this.inputs.attached["keyboard"];
  40508. if (keyboard)
  40509. return keyboard.keysUp;
  40510. return [];
  40511. },
  40512. set: function (value) {
  40513. var keyboard = this.inputs.attached["keyboard"];
  40514. if (keyboard)
  40515. keyboard.keysUp = value;
  40516. },
  40517. enumerable: true,
  40518. configurable: true
  40519. });
  40520. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  40521. get: function () {
  40522. var keyboard = this.inputs.attached["keyboard"];
  40523. if (keyboard)
  40524. return keyboard.keysDown;
  40525. return [];
  40526. },
  40527. set: function (value) {
  40528. var keyboard = this.inputs.attached["keyboard"];
  40529. if (keyboard)
  40530. keyboard.keysDown = value;
  40531. },
  40532. enumerable: true,
  40533. configurable: true
  40534. });
  40535. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  40536. get: function () {
  40537. var keyboard = this.inputs.attached["keyboard"];
  40538. if (keyboard)
  40539. return keyboard.keysLeft;
  40540. return [];
  40541. },
  40542. set: function (value) {
  40543. var keyboard = this.inputs.attached["keyboard"];
  40544. if (keyboard)
  40545. keyboard.keysLeft = value;
  40546. },
  40547. enumerable: true,
  40548. configurable: true
  40549. });
  40550. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  40551. get: function () {
  40552. var keyboard = this.inputs.attached["keyboard"];
  40553. if (keyboard)
  40554. return keyboard.keysRight;
  40555. return [];
  40556. },
  40557. set: function (value) {
  40558. var keyboard = this.inputs.attached["keyboard"];
  40559. if (keyboard)
  40560. keyboard.keysRight = value;
  40561. },
  40562. enumerable: true,
  40563. configurable: true
  40564. });
  40565. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  40566. get: function () {
  40567. var mousewheel = this.inputs.attached["mousewheel"];
  40568. if (mousewheel)
  40569. return mousewheel.wheelPrecision;
  40570. return 0;
  40571. },
  40572. set: function (value) {
  40573. var mousewheel = this.inputs.attached["mousewheel"];
  40574. if (mousewheel)
  40575. mousewheel.wheelPrecision = value;
  40576. },
  40577. enumerable: true,
  40578. configurable: true
  40579. });
  40580. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  40581. get: function () {
  40582. var mousewheel = this.inputs.attached["mousewheel"];
  40583. if (mousewheel)
  40584. return mousewheel.wheelDeltaPercentage;
  40585. return 0;
  40586. },
  40587. set: function (value) {
  40588. var mousewheel = this.inputs.attached["mousewheel"];
  40589. if (mousewheel)
  40590. mousewheel.wheelDeltaPercentage = value;
  40591. },
  40592. enumerable: true,
  40593. configurable: true
  40594. });
  40595. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  40596. get: function () {
  40597. return this._bouncingBehavior;
  40598. },
  40599. enumerable: true,
  40600. configurable: true
  40601. });
  40602. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  40603. get: function () {
  40604. return this._bouncingBehavior != null;
  40605. },
  40606. set: function (value) {
  40607. if (value === this.useBouncingBehavior) {
  40608. return;
  40609. }
  40610. if (value) {
  40611. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  40612. this.addBehavior(this._bouncingBehavior);
  40613. }
  40614. else if (this._bouncingBehavior) {
  40615. this.removeBehavior(this._bouncingBehavior);
  40616. this._bouncingBehavior = null;
  40617. }
  40618. },
  40619. enumerable: true,
  40620. configurable: true
  40621. });
  40622. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  40623. get: function () {
  40624. return this._framingBehavior;
  40625. },
  40626. enumerable: true,
  40627. configurable: true
  40628. });
  40629. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  40630. get: function () {
  40631. return this._framingBehavior != null;
  40632. },
  40633. set: function (value) {
  40634. if (value === this.useFramingBehavior) {
  40635. return;
  40636. }
  40637. if (value) {
  40638. this._framingBehavior = new BABYLON.FramingBehavior();
  40639. this.addBehavior(this._framingBehavior);
  40640. }
  40641. else if (this._framingBehavior) {
  40642. this.removeBehavior(this._framingBehavior);
  40643. this._framingBehavior = null;
  40644. }
  40645. },
  40646. enumerable: true,
  40647. configurable: true
  40648. });
  40649. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  40650. get: function () {
  40651. return this._autoRotationBehavior;
  40652. },
  40653. enumerable: true,
  40654. configurable: true
  40655. });
  40656. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  40657. get: function () {
  40658. return this._autoRotationBehavior != null;
  40659. },
  40660. set: function (value) {
  40661. if (value === this.useAutoRotationBehavior) {
  40662. return;
  40663. }
  40664. if (value) {
  40665. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  40666. this.addBehavior(this._autoRotationBehavior);
  40667. }
  40668. else if (this._autoRotationBehavior) {
  40669. this.removeBehavior(this._autoRotationBehavior);
  40670. this._autoRotationBehavior = null;
  40671. }
  40672. },
  40673. enumerable: true,
  40674. configurable: true
  40675. });
  40676. // Cache
  40677. ArcRotateCamera.prototype._initCache = function () {
  40678. _super.prototype._initCache.call(this);
  40679. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40680. this._cache.alpha = undefined;
  40681. this._cache.beta = undefined;
  40682. this._cache.radius = undefined;
  40683. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  40684. };
  40685. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  40686. if (!ignoreParentClass) {
  40687. _super.prototype._updateCache.call(this);
  40688. }
  40689. this._cache._target.copyFrom(this._getTargetPosition());
  40690. this._cache.alpha = this.alpha;
  40691. this._cache.beta = this.beta;
  40692. this._cache.radius = this.radius;
  40693. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  40694. };
  40695. ArcRotateCamera.prototype._getTargetPosition = function () {
  40696. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  40697. var pos = this._targetHost.getAbsolutePosition();
  40698. if (this._targetBoundingCenter) {
  40699. pos.addToRef(this._targetBoundingCenter, this._target);
  40700. }
  40701. else {
  40702. this._target.copyFrom(pos);
  40703. }
  40704. }
  40705. var lockedTargetPosition = this._getLockedTargetPosition();
  40706. if (lockedTargetPosition) {
  40707. return lockedTargetPosition;
  40708. }
  40709. return this._target;
  40710. };
  40711. ArcRotateCamera.prototype.storeState = function () {
  40712. this._storedAlpha = this.alpha;
  40713. this._storedBeta = this.beta;
  40714. this._storedRadius = this.radius;
  40715. this._storedTarget = this._getTargetPosition().clone();
  40716. return _super.prototype.storeState.call(this);
  40717. };
  40718. /**
  40719. * Restored camera state. You must call storeState() first
  40720. */
  40721. ArcRotateCamera.prototype._restoreStateValues = function () {
  40722. if (!_super.prototype._restoreStateValues.call(this)) {
  40723. return false;
  40724. }
  40725. this.alpha = this._storedAlpha;
  40726. this.beta = this._storedBeta;
  40727. this.radius = this._storedRadius;
  40728. this.setTarget(this._storedTarget.clone());
  40729. this.inertialAlphaOffset = 0;
  40730. this.inertialBetaOffset = 0;
  40731. this.inertialRadiusOffset = 0;
  40732. this.inertialPanningX = 0;
  40733. this.inertialPanningY = 0;
  40734. return true;
  40735. };
  40736. // Synchronized
  40737. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  40738. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  40739. return false;
  40740. return this._cache._target.equals(this._getTargetPosition())
  40741. && this._cache.alpha === this.alpha
  40742. && this._cache.beta === this.beta
  40743. && this._cache.radius === this.radius
  40744. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  40745. };
  40746. // Methods
  40747. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  40748. var _this = this;
  40749. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  40750. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  40751. this._useCtrlForPanning = useCtrlForPanning;
  40752. this._panningMouseButton = panningMouseButton;
  40753. this.inputs.attachElement(element, noPreventDefault);
  40754. this._reset = function () {
  40755. _this.inertialAlphaOffset = 0;
  40756. _this.inertialBetaOffset = 0;
  40757. _this.inertialRadiusOffset = 0;
  40758. _this.inertialPanningX = 0;
  40759. _this.inertialPanningY = 0;
  40760. };
  40761. };
  40762. ArcRotateCamera.prototype.detachControl = function (element) {
  40763. this.inputs.detachElement(element);
  40764. if (this._reset) {
  40765. this._reset();
  40766. }
  40767. };
  40768. ArcRotateCamera.prototype._checkInputs = function () {
  40769. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  40770. if (this._collisionTriggered) {
  40771. return;
  40772. }
  40773. this.inputs.checkInputs();
  40774. // Inertia
  40775. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  40776. if (this.getScene().useRightHandedSystem) {
  40777. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40778. }
  40779. else {
  40780. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40781. }
  40782. this.beta += this.inertialBetaOffset;
  40783. this.radius -= this.inertialRadiusOffset;
  40784. this.inertialAlphaOffset *= this.inertia;
  40785. this.inertialBetaOffset *= this.inertia;
  40786. this.inertialRadiusOffset *= this.inertia;
  40787. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  40788. this.inertialAlphaOffset = 0;
  40789. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  40790. this.inertialBetaOffset = 0;
  40791. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  40792. this.inertialRadiusOffset = 0;
  40793. }
  40794. // Panning inertia
  40795. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  40796. if (!this._localDirection) {
  40797. this._localDirection = BABYLON.Vector3.Zero();
  40798. this._transformedDirection = BABYLON.Vector3.Zero();
  40799. }
  40800. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  40801. this._localDirection.multiplyInPlace(this.panningAxis);
  40802. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  40803. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  40804. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  40805. if (!this.panningAxis.y) {
  40806. this._transformedDirection.y = 0;
  40807. }
  40808. if (!this._targetHost) {
  40809. if (this.panningDistanceLimit) {
  40810. this._transformedDirection.addInPlace(this._target);
  40811. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  40812. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  40813. this._target.copyFrom(this._transformedDirection);
  40814. }
  40815. }
  40816. else {
  40817. this._target.addInPlace(this._transformedDirection);
  40818. }
  40819. }
  40820. this.inertialPanningX *= this.panningInertia;
  40821. this.inertialPanningY *= this.panningInertia;
  40822. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  40823. this.inertialPanningX = 0;
  40824. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  40825. this.inertialPanningY = 0;
  40826. }
  40827. // Limits
  40828. this._checkLimits();
  40829. _super.prototype._checkInputs.call(this);
  40830. };
  40831. ArcRotateCamera.prototype._checkLimits = function () {
  40832. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  40833. if (this.allowUpsideDown && this.beta > Math.PI) {
  40834. this.beta = this.beta - (2 * Math.PI);
  40835. }
  40836. }
  40837. else {
  40838. if (this.beta < this.lowerBetaLimit) {
  40839. this.beta = this.lowerBetaLimit;
  40840. }
  40841. }
  40842. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  40843. if (this.allowUpsideDown && this.beta < -Math.PI) {
  40844. this.beta = this.beta + (2 * Math.PI);
  40845. }
  40846. }
  40847. else {
  40848. if (this.beta > this.upperBetaLimit) {
  40849. this.beta = this.upperBetaLimit;
  40850. }
  40851. }
  40852. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  40853. this.alpha = this.lowerAlphaLimit;
  40854. }
  40855. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  40856. this.alpha = this.upperAlphaLimit;
  40857. }
  40858. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  40859. this.radius = this.lowerRadiusLimit;
  40860. }
  40861. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  40862. this.radius = this.upperRadiusLimit;
  40863. }
  40864. };
  40865. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  40866. var radiusv3 = this.position.subtract(this._getTargetPosition());
  40867. this.radius = radiusv3.length();
  40868. if (this.radius === 0) {
  40869. this.radius = 0.0001; // Just to avoid division by zero
  40870. }
  40871. // Alpha
  40872. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  40873. if (radiusv3.z < 0) {
  40874. this.alpha = 2 * Math.PI - this.alpha;
  40875. }
  40876. // Beta
  40877. this.beta = Math.acos(radiusv3.y / this.radius);
  40878. this._checkLimits();
  40879. };
  40880. ArcRotateCamera.prototype.setPosition = function (position) {
  40881. if (this.position.equals(position)) {
  40882. return;
  40883. }
  40884. this.position.copyFrom(position);
  40885. this.rebuildAnglesAndRadius();
  40886. };
  40887. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  40888. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  40889. if (allowSamePosition === void 0) { allowSamePosition = false; }
  40890. if (target.getBoundingInfo) {
  40891. if (toBoundingCenter) {
  40892. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  40893. }
  40894. else {
  40895. this._targetBoundingCenter = null;
  40896. }
  40897. this._targetHost = target;
  40898. this._target = this._getTargetPosition();
  40899. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  40900. }
  40901. else {
  40902. var newTarget = target;
  40903. var currentTarget = this._getTargetPosition();
  40904. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  40905. return;
  40906. }
  40907. this._targetHost = null;
  40908. this._target = newTarget;
  40909. this._targetBoundingCenter = null;
  40910. this.onMeshTargetChangedObservable.notifyObservers(null);
  40911. }
  40912. this.rebuildAnglesAndRadius();
  40913. };
  40914. ArcRotateCamera.prototype._getViewMatrix = function () {
  40915. // Compute
  40916. var cosa = Math.cos(this.alpha);
  40917. var sina = Math.sin(this.alpha);
  40918. var cosb = Math.cos(this.beta);
  40919. var sinb = Math.sin(this.beta);
  40920. if (sinb === 0) {
  40921. sinb = 0.0001;
  40922. }
  40923. var target = this._getTargetPosition();
  40924. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  40925. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  40926. if (!this._collider) {
  40927. this._collider = new BABYLON.Collider();
  40928. }
  40929. this._collider._radius = this.collisionRadius;
  40930. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  40931. this._collisionTriggered = true;
  40932. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40933. }
  40934. else {
  40935. this.position.copyFrom(this._newPosition);
  40936. var up = this.upVector;
  40937. if (this.allowUpsideDown && sinb < 0) {
  40938. up = up.clone();
  40939. up = up.negate();
  40940. }
  40941. if (this.getScene().useRightHandedSystem) {
  40942. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  40943. }
  40944. else {
  40945. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  40946. }
  40947. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  40948. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  40949. }
  40950. this._currentTarget = target;
  40951. return this._viewMatrix;
  40952. };
  40953. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  40954. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40955. meshes = meshes || this.getScene().meshes;
  40956. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  40957. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  40958. this.radius = distance * this.zoomOnFactor;
  40959. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  40960. };
  40961. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  40962. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40963. var meshesOrMinMaxVector;
  40964. var distance;
  40965. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  40966. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  40967. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  40968. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  40969. }
  40970. else {
  40971. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  40972. meshesOrMinMaxVector = minMaxVectorAndDistance;
  40973. distance = minMaxVectorAndDistance.distance;
  40974. }
  40975. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  40976. if (!doNotUpdateMaxZ) {
  40977. this.maxZ = distance * 2;
  40978. }
  40979. };
  40980. /**
  40981. * @override
  40982. * Override Camera.createRigCamera
  40983. */
  40984. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40985. var alphaShift = 0;
  40986. switch (this.cameraRigMode) {
  40987. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40988. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40989. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40990. case BABYLON.Camera.RIG_MODE_VR:
  40991. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  40992. break;
  40993. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40994. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  40995. break;
  40996. }
  40997. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  40998. rigCam._cameraRigParams = {};
  40999. return rigCam;
  41000. };
  41001. /**
  41002. * @override
  41003. * Override Camera._updateRigCameras
  41004. */
  41005. ArcRotateCamera.prototype._updateRigCameras = function () {
  41006. var camLeft = this._rigCameras[0];
  41007. var camRight = this._rigCameras[1];
  41008. camLeft.beta = camRight.beta = this.beta;
  41009. camLeft.radius = camRight.radius = this.radius;
  41010. switch (this.cameraRigMode) {
  41011. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  41012. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  41013. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  41014. case BABYLON.Camera.RIG_MODE_VR:
  41015. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  41016. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  41017. break;
  41018. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  41019. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  41020. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  41021. break;
  41022. }
  41023. _super.prototype._updateRigCameras.call(this);
  41024. };
  41025. ArcRotateCamera.prototype.dispose = function () {
  41026. this.inputs.clear();
  41027. _super.prototype.dispose.call(this);
  41028. };
  41029. ArcRotateCamera.prototype.getClassName = function () {
  41030. return "ArcRotateCamera";
  41031. };
  41032. __decorate([
  41033. BABYLON.serialize()
  41034. ], ArcRotateCamera.prototype, "alpha", void 0);
  41035. __decorate([
  41036. BABYLON.serialize()
  41037. ], ArcRotateCamera.prototype, "beta", void 0);
  41038. __decorate([
  41039. BABYLON.serialize()
  41040. ], ArcRotateCamera.prototype, "radius", void 0);
  41041. __decorate([
  41042. BABYLON.serializeAsVector3("target")
  41043. ], ArcRotateCamera.prototype, "_target", void 0);
  41044. __decorate([
  41045. BABYLON.serialize()
  41046. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  41047. __decorate([
  41048. BABYLON.serialize()
  41049. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  41050. __decorate([
  41051. BABYLON.serialize()
  41052. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  41053. __decorate([
  41054. BABYLON.serialize()
  41055. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  41056. __decorate([
  41057. BABYLON.serialize()
  41058. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  41059. __decorate([
  41060. BABYLON.serialize()
  41061. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  41062. __decorate([
  41063. BABYLON.serialize()
  41064. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  41065. __decorate([
  41066. BABYLON.serialize()
  41067. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  41068. __decorate([
  41069. BABYLON.serialize()
  41070. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  41071. __decorate([
  41072. BABYLON.serialize()
  41073. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  41074. __decorate([
  41075. BABYLON.serialize()
  41076. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  41077. __decorate([
  41078. BABYLON.serialize()
  41079. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  41080. __decorate([
  41081. BABYLON.serialize()
  41082. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  41083. __decorate([
  41084. BABYLON.serializeAsVector3()
  41085. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  41086. __decorate([
  41087. BABYLON.serialize()
  41088. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  41089. __decorate([
  41090. BABYLON.serialize()
  41091. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  41092. __decorate([
  41093. BABYLON.serialize()
  41094. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  41095. return ArcRotateCamera;
  41096. }(BABYLON.TargetCamera));
  41097. BABYLON.ArcRotateCamera = ArcRotateCamera;
  41098. })(BABYLON || (BABYLON = {}));
  41099. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  41100. var BABYLON;
  41101. (function (BABYLON) {
  41102. var HemisphericLight = /** @class */ (function (_super) {
  41103. __extends(HemisphericLight, _super);
  41104. /**
  41105. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  41106. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  41107. * The HemisphericLight can't cast shadows.
  41108. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41109. */
  41110. function HemisphericLight(name, direction, scene) {
  41111. var _this = _super.call(this, name, scene) || this;
  41112. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  41113. _this.direction = direction || BABYLON.Vector3.Up();
  41114. return _this;
  41115. }
  41116. HemisphericLight.prototype._buildUniformLayout = function () {
  41117. this._uniformBuffer.addUniform("vLightData", 4);
  41118. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41119. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41120. this._uniformBuffer.addUniform("vLightGround", 3);
  41121. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41122. this._uniformBuffer.addUniform("depthValues", 2);
  41123. this._uniformBuffer.create();
  41124. };
  41125. /**
  41126. * Returns the string "HemisphericLight".
  41127. */
  41128. HemisphericLight.prototype.getClassName = function () {
  41129. return "HemisphericLight";
  41130. };
  41131. /**
  41132. * Sets the HemisphericLight direction towards the passed target (Vector3).
  41133. * Returns the updated direction.
  41134. */
  41135. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  41136. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  41137. return this.direction;
  41138. };
  41139. HemisphericLight.prototype.getShadowGenerator = function () {
  41140. return null;
  41141. };
  41142. /**
  41143. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  41144. * Returns the HemisphericLight.
  41145. */
  41146. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  41147. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41148. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  41149. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  41150. return this;
  41151. };
  41152. HemisphericLight.prototype._getWorldMatrix = function () {
  41153. if (!this._worldMatrix) {
  41154. this._worldMatrix = BABYLON.Matrix.Identity();
  41155. }
  41156. return this._worldMatrix;
  41157. };
  41158. /**
  41159. * Returns the integer 3.
  41160. */
  41161. HemisphericLight.prototype.getTypeID = function () {
  41162. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  41163. };
  41164. __decorate([
  41165. BABYLON.serializeAsColor3()
  41166. ], HemisphericLight.prototype, "groundColor", void 0);
  41167. __decorate([
  41168. BABYLON.serializeAsVector3()
  41169. ], HemisphericLight.prototype, "direction", void 0);
  41170. return HemisphericLight;
  41171. }(BABYLON.Light));
  41172. BABYLON.HemisphericLight = HemisphericLight;
  41173. })(BABYLON || (BABYLON = {}));
  41174. //# sourceMappingURL=babylon.hemisphericLight.js.map
  41175. var BABYLON;
  41176. (function (BABYLON) {
  41177. var ShadowLight = /** @class */ (function (_super) {
  41178. __extends(ShadowLight, _super);
  41179. function ShadowLight() {
  41180. var _this = _super !== null && _super.apply(this, arguments) || this;
  41181. _this._needProjectionMatrixCompute = true;
  41182. return _this;
  41183. }
  41184. Object.defineProperty(ShadowLight.prototype, "direction", {
  41185. get: function () {
  41186. return this._direction;
  41187. },
  41188. set: function (value) {
  41189. this._direction = value;
  41190. },
  41191. enumerable: true,
  41192. configurable: true
  41193. });
  41194. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  41195. get: function () {
  41196. return this._shadowMinZ;
  41197. },
  41198. set: function (value) {
  41199. this._shadowMinZ = value;
  41200. this.forceProjectionMatrixCompute();
  41201. },
  41202. enumerable: true,
  41203. configurable: true
  41204. });
  41205. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  41206. get: function () {
  41207. return this._shadowMaxZ;
  41208. },
  41209. set: function (value) {
  41210. this._shadowMaxZ = value;
  41211. this.forceProjectionMatrixCompute();
  41212. },
  41213. enumerable: true,
  41214. configurable: true
  41215. });
  41216. /**
  41217. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  41218. */
  41219. ShadowLight.prototype.computeTransformedInformation = function () {
  41220. if (this.parent && this.parent.getWorldMatrix) {
  41221. if (!this.transformedPosition) {
  41222. this.transformedPosition = BABYLON.Vector3.Zero();
  41223. }
  41224. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  41225. // In case the direction is present.
  41226. if (this.direction) {
  41227. if (!this.transformedDirection) {
  41228. this.transformedDirection = BABYLON.Vector3.Zero();
  41229. }
  41230. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  41231. }
  41232. return true;
  41233. }
  41234. return false;
  41235. };
  41236. /**
  41237. * Return the depth scale used for the shadow map.
  41238. */
  41239. ShadowLight.prototype.getDepthScale = function () {
  41240. return 50.0;
  41241. };
  41242. /**
  41243. * Returns the light direction (Vector3) for any passed face index.
  41244. */
  41245. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  41246. return this.transformedDirection ? this.transformedDirection : this.direction;
  41247. };
  41248. /**
  41249. * Returns the ShadowLight absolute position in the World.
  41250. */
  41251. ShadowLight.prototype.getAbsolutePosition = function () {
  41252. return this.transformedPosition ? this.transformedPosition : this.position;
  41253. };
  41254. /**
  41255. * Sets the ShadowLight direction toward the passed target (Vector3).
  41256. * Returns the updated ShadowLight direction (Vector3).
  41257. */
  41258. ShadowLight.prototype.setDirectionToTarget = function (target) {
  41259. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  41260. return this.direction;
  41261. };
  41262. /**
  41263. * Returns the light rotation (Vector3).
  41264. */
  41265. ShadowLight.prototype.getRotation = function () {
  41266. this.direction.normalize();
  41267. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  41268. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  41269. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  41270. };
  41271. /**
  41272. * Boolean : false by default.
  41273. */
  41274. ShadowLight.prototype.needCube = function () {
  41275. return false;
  41276. };
  41277. /**
  41278. * Specifies wether or not the projection matrix should be recomputed this frame.
  41279. */
  41280. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  41281. return this._needProjectionMatrixCompute;
  41282. };
  41283. /**
  41284. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  41285. */
  41286. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  41287. this._needProjectionMatrixCompute = true;
  41288. };
  41289. /**
  41290. * Get the world matrix of the sahdow lights.
  41291. */
  41292. ShadowLight.prototype._getWorldMatrix = function () {
  41293. if (!this._worldMatrix) {
  41294. this._worldMatrix = BABYLON.Matrix.Identity();
  41295. }
  41296. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  41297. return this._worldMatrix;
  41298. };
  41299. /**
  41300. * Gets the minZ used for shadow according to both the scene and the light.
  41301. * @param activeCamera
  41302. */
  41303. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  41304. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  41305. };
  41306. /**
  41307. * Gets the maxZ used for shadow according to both the scene and the light.
  41308. * @param activeCamera
  41309. */
  41310. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  41311. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  41312. };
  41313. /**
  41314. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  41315. * Returns the light.
  41316. */
  41317. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41318. if (this.customProjectionMatrixBuilder) {
  41319. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  41320. }
  41321. else {
  41322. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  41323. }
  41324. return this;
  41325. };
  41326. __decorate([
  41327. BABYLON.serializeAsVector3()
  41328. ], ShadowLight.prototype, "position", void 0);
  41329. __decorate([
  41330. BABYLON.serializeAsVector3()
  41331. ], ShadowLight.prototype, "direction", null);
  41332. __decorate([
  41333. BABYLON.serialize()
  41334. ], ShadowLight.prototype, "shadowMinZ", null);
  41335. __decorate([
  41336. BABYLON.serialize()
  41337. ], ShadowLight.prototype, "shadowMaxZ", null);
  41338. return ShadowLight;
  41339. }(BABYLON.Light));
  41340. BABYLON.ShadowLight = ShadowLight;
  41341. })(BABYLON || (BABYLON = {}));
  41342. //# sourceMappingURL=babylon.shadowLight.js.map
  41343. var BABYLON;
  41344. (function (BABYLON) {
  41345. var PointLight = /** @class */ (function (_super) {
  41346. __extends(PointLight, _super);
  41347. /**
  41348. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  41349. * A PointLight emits the light in every direction.
  41350. * It can cast shadows.
  41351. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  41352. * ```javascript
  41353. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  41354. * ```
  41355. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41356. */
  41357. function PointLight(name, position, scene) {
  41358. var _this = _super.call(this, name, scene) || this;
  41359. _this._shadowAngle = Math.PI / 2;
  41360. _this.position = position;
  41361. return _this;
  41362. }
  41363. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  41364. /**
  41365. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41366. * This specifies what angle the shadow will use to be created.
  41367. *
  41368. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  41369. */
  41370. get: function () {
  41371. return this._shadowAngle;
  41372. },
  41373. /**
  41374. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41375. * This specifies what angle the shadow will use to be created.
  41376. *
  41377. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  41378. */
  41379. set: function (value) {
  41380. this._shadowAngle = value;
  41381. this.forceProjectionMatrixCompute();
  41382. },
  41383. enumerable: true,
  41384. configurable: true
  41385. });
  41386. Object.defineProperty(PointLight.prototype, "direction", {
  41387. get: function () {
  41388. return this._direction;
  41389. },
  41390. /**
  41391. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41392. */
  41393. set: function (value) {
  41394. var previousNeedCube = this.needCube();
  41395. this._direction = value;
  41396. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  41397. this._shadowGenerator.recreateShadowMap();
  41398. }
  41399. },
  41400. enumerable: true,
  41401. configurable: true
  41402. });
  41403. /**
  41404. * Returns the string "PointLight"
  41405. */
  41406. PointLight.prototype.getClassName = function () {
  41407. return "PointLight";
  41408. };
  41409. /**
  41410. * Returns the integer 0.
  41411. */
  41412. PointLight.prototype.getTypeID = function () {
  41413. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  41414. };
  41415. /**
  41416. * Specifies wether or not the shadowmap should be a cube texture.
  41417. */
  41418. PointLight.prototype.needCube = function () {
  41419. return !this.direction;
  41420. };
  41421. /**
  41422. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  41423. */
  41424. PointLight.prototype.getShadowDirection = function (faceIndex) {
  41425. if (this.direction) {
  41426. return _super.prototype.getShadowDirection.call(this, faceIndex);
  41427. }
  41428. else {
  41429. switch (faceIndex) {
  41430. case 0:
  41431. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  41432. case 1:
  41433. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  41434. case 2:
  41435. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  41436. case 3:
  41437. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  41438. case 4:
  41439. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  41440. case 5:
  41441. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  41442. }
  41443. }
  41444. return BABYLON.Vector3.Zero();
  41445. };
  41446. /**
  41447. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  41448. * - fov = PI / 2
  41449. * - aspect ratio : 1.0
  41450. * - z-near and far equal to the active camera minZ and maxZ.
  41451. * Returns the PointLight.
  41452. */
  41453. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41454. var activeCamera = this.getScene().activeCamera;
  41455. if (!activeCamera) {
  41456. return;
  41457. }
  41458. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41459. };
  41460. PointLight.prototype._buildUniformLayout = function () {
  41461. this._uniformBuffer.addUniform("vLightData", 4);
  41462. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41463. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41464. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41465. this._uniformBuffer.addUniform("depthValues", 2);
  41466. this._uniformBuffer.create();
  41467. };
  41468. /**
  41469. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  41470. * Returns the PointLight.
  41471. */
  41472. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  41473. if (this.computeTransformedInformation()) {
  41474. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  41475. return this;
  41476. }
  41477. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  41478. return this;
  41479. };
  41480. __decorate([
  41481. BABYLON.serialize()
  41482. ], PointLight.prototype, "shadowAngle", null);
  41483. return PointLight;
  41484. }(BABYLON.ShadowLight));
  41485. BABYLON.PointLight = PointLight;
  41486. })(BABYLON || (BABYLON = {}));
  41487. //# sourceMappingURL=babylon.pointLight.js.map
  41488. var BABYLON;
  41489. (function (BABYLON) {
  41490. var DirectionalLight = /** @class */ (function (_super) {
  41491. __extends(DirectionalLight, _super);
  41492. /**
  41493. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  41494. * The directional light is emitted from everywhere in the given direction.
  41495. * It can cast shawdows.
  41496. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41497. */
  41498. function DirectionalLight(name, direction, scene) {
  41499. var _this = _super.call(this, name, scene) || this;
  41500. _this._shadowFrustumSize = 0;
  41501. _this._shadowOrthoScale = 0.5;
  41502. _this.autoUpdateExtends = true;
  41503. // Cache
  41504. _this._orthoLeft = Number.MAX_VALUE;
  41505. _this._orthoRight = Number.MIN_VALUE;
  41506. _this._orthoTop = Number.MIN_VALUE;
  41507. _this._orthoBottom = Number.MAX_VALUE;
  41508. _this.position = direction.scale(-1.0);
  41509. _this.direction = direction;
  41510. return _this;
  41511. }
  41512. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  41513. /**
  41514. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  41515. */
  41516. get: function () {
  41517. return this._shadowFrustumSize;
  41518. },
  41519. /**
  41520. * Specifies a fix frustum size for the shadow generation.
  41521. */
  41522. set: function (value) {
  41523. this._shadowFrustumSize = value;
  41524. this.forceProjectionMatrixCompute();
  41525. },
  41526. enumerable: true,
  41527. configurable: true
  41528. });
  41529. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  41530. get: function () {
  41531. return this._shadowOrthoScale;
  41532. },
  41533. set: function (value) {
  41534. this._shadowOrthoScale = value;
  41535. this.forceProjectionMatrixCompute();
  41536. },
  41537. enumerable: true,
  41538. configurable: true
  41539. });
  41540. /**
  41541. * Returns the string "DirectionalLight".
  41542. */
  41543. DirectionalLight.prototype.getClassName = function () {
  41544. return "DirectionalLight";
  41545. };
  41546. /**
  41547. * Returns the integer 1.
  41548. */
  41549. DirectionalLight.prototype.getTypeID = function () {
  41550. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  41551. };
  41552. /**
  41553. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  41554. * Returns the DirectionalLight Shadow projection matrix.
  41555. */
  41556. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41557. if (this.shadowFrustumSize > 0) {
  41558. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  41559. }
  41560. else {
  41561. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  41562. }
  41563. };
  41564. /**
  41565. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  41566. * Returns the DirectionalLight Shadow projection matrix.
  41567. */
  41568. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  41569. var activeCamera = this.getScene().activeCamera;
  41570. if (!activeCamera) {
  41571. return;
  41572. }
  41573. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  41574. };
  41575. /**
  41576. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  41577. * Returns the DirectionalLight Shadow projection matrix.
  41578. */
  41579. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41580. var activeCamera = this.getScene().activeCamera;
  41581. if (!activeCamera) {
  41582. return;
  41583. }
  41584. // Check extends
  41585. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  41586. var tempVector3 = BABYLON.Vector3.Zero();
  41587. this._orthoLeft = Number.MAX_VALUE;
  41588. this._orthoRight = Number.MIN_VALUE;
  41589. this._orthoTop = Number.MIN_VALUE;
  41590. this._orthoBottom = Number.MAX_VALUE;
  41591. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  41592. var mesh = renderList[meshIndex];
  41593. if (!mesh) {
  41594. continue;
  41595. }
  41596. var boundingInfo = mesh.getBoundingInfo();
  41597. var boundingBox = boundingInfo.boundingBox;
  41598. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  41599. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  41600. if (tempVector3.x < this._orthoLeft)
  41601. this._orthoLeft = tempVector3.x;
  41602. if (tempVector3.y < this._orthoBottom)
  41603. this._orthoBottom = tempVector3.y;
  41604. if (tempVector3.x > this._orthoRight)
  41605. this._orthoRight = tempVector3.x;
  41606. if (tempVector3.y > this._orthoTop)
  41607. this._orthoTop = tempVector3.y;
  41608. }
  41609. }
  41610. }
  41611. var xOffset = this._orthoRight - this._orthoLeft;
  41612. var yOffset = this._orthoTop - this._orthoBottom;
  41613. 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);
  41614. };
  41615. DirectionalLight.prototype._buildUniformLayout = function () {
  41616. this._uniformBuffer.addUniform("vLightData", 4);
  41617. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41618. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41619. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41620. this._uniformBuffer.addUniform("depthValues", 2);
  41621. this._uniformBuffer.create();
  41622. };
  41623. /**
  41624. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  41625. * Returns the DirectionalLight.
  41626. */
  41627. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  41628. if (this.computeTransformedInformation()) {
  41629. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  41630. return this;
  41631. }
  41632. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  41633. return this;
  41634. };
  41635. /**
  41636. * Gets the minZ used for shadow according to both the scene and the light.
  41637. *
  41638. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41639. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41640. * @param activeCamera
  41641. */
  41642. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  41643. return 1;
  41644. };
  41645. /**
  41646. * Gets the maxZ used for shadow according to both the scene and the light.
  41647. *
  41648. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41649. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41650. * @param activeCamera
  41651. */
  41652. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  41653. return 1;
  41654. };
  41655. __decorate([
  41656. BABYLON.serialize()
  41657. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  41658. __decorate([
  41659. BABYLON.serialize()
  41660. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  41661. __decorate([
  41662. BABYLON.serialize()
  41663. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  41664. return DirectionalLight;
  41665. }(BABYLON.ShadowLight));
  41666. BABYLON.DirectionalLight = DirectionalLight;
  41667. })(BABYLON || (BABYLON = {}));
  41668. //# sourceMappingURL=babylon.directionalLight.js.map
  41669. var BABYLON;
  41670. (function (BABYLON) {
  41671. var SpotLight = /** @class */ (function (_super) {
  41672. __extends(SpotLight, _super);
  41673. /**
  41674. * Creates a SpotLight object in the scene with the passed parameters :
  41675. * - `position` (Vector3) is the initial SpotLight position,
  41676. * - `direction` (Vector3) is the initial SpotLight direction,
  41677. * - `angle` (float, in radians) is the spot light cone angle,
  41678. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  41679. * A spot light is a simply light oriented cone.
  41680. * It can cast shadows.
  41681. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41682. */
  41683. function SpotLight(name, position, direction, angle, exponent, scene) {
  41684. var _this = _super.call(this, name, scene) || this;
  41685. _this.position = position;
  41686. _this.direction = direction;
  41687. _this.angle = angle;
  41688. _this.exponent = exponent;
  41689. return _this;
  41690. }
  41691. Object.defineProperty(SpotLight.prototype, "angle", {
  41692. get: function () {
  41693. return this._angle;
  41694. },
  41695. set: function (value) {
  41696. this._angle = value;
  41697. this.forceProjectionMatrixCompute();
  41698. },
  41699. enumerable: true,
  41700. configurable: true
  41701. });
  41702. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  41703. get: function () {
  41704. return this._shadowAngleScale;
  41705. },
  41706. /**
  41707. * Allows scaling the angle of the light for shadow generation only.
  41708. */
  41709. set: function (value) {
  41710. this._shadowAngleScale = value;
  41711. this.forceProjectionMatrixCompute();
  41712. },
  41713. enumerable: true,
  41714. configurable: true
  41715. });
  41716. /**
  41717. * Returns the string "SpotLight".
  41718. */
  41719. SpotLight.prototype.getClassName = function () {
  41720. return "SpotLight";
  41721. };
  41722. /**
  41723. * Returns the integer 2.
  41724. */
  41725. SpotLight.prototype.getTypeID = function () {
  41726. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  41727. };
  41728. /**
  41729. * 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.
  41730. * Returns the SpotLight.
  41731. */
  41732. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41733. var activeCamera = this.getScene().activeCamera;
  41734. if (!activeCamera) {
  41735. return;
  41736. }
  41737. this._shadowAngleScale = this._shadowAngleScale || 1;
  41738. var angle = this._shadowAngleScale * this._angle;
  41739. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41740. };
  41741. SpotLight.prototype._buildUniformLayout = function () {
  41742. this._uniformBuffer.addUniform("vLightData", 4);
  41743. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41744. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41745. this._uniformBuffer.addUniform("vLightDirection", 3);
  41746. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41747. this._uniformBuffer.addUniform("depthValues", 2);
  41748. this._uniformBuffer.create();
  41749. };
  41750. /**
  41751. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  41752. * Return the SpotLight.
  41753. */
  41754. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  41755. var normalizeDirection;
  41756. if (this.computeTransformedInformation()) {
  41757. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  41758. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  41759. }
  41760. else {
  41761. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  41762. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41763. }
  41764. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  41765. return this;
  41766. };
  41767. __decorate([
  41768. BABYLON.serialize()
  41769. ], SpotLight.prototype, "angle", null);
  41770. __decorate([
  41771. BABYLON.serialize()
  41772. /**
  41773. * Allows scaling the angle of the light for shadow generation only.
  41774. */
  41775. ], SpotLight.prototype, "shadowAngleScale", null);
  41776. __decorate([
  41777. BABYLON.serialize()
  41778. ], SpotLight.prototype, "exponent", void 0);
  41779. return SpotLight;
  41780. }(BABYLON.ShadowLight));
  41781. BABYLON.SpotLight = SpotLight;
  41782. })(BABYLON || (BABYLON = {}));
  41783. //# sourceMappingURL=babylon.spotLight.js.map
  41784. var BABYLON;
  41785. (function (BABYLON) {
  41786. var AnimationRange = /** @class */ (function () {
  41787. function AnimationRange(name, from, to) {
  41788. this.name = name;
  41789. this.from = from;
  41790. this.to = to;
  41791. }
  41792. AnimationRange.prototype.clone = function () {
  41793. return new AnimationRange(this.name, this.from, this.to);
  41794. };
  41795. return AnimationRange;
  41796. }());
  41797. BABYLON.AnimationRange = AnimationRange;
  41798. /**
  41799. * Composed of a frame, and an action function
  41800. */
  41801. var AnimationEvent = /** @class */ (function () {
  41802. function AnimationEvent(frame, action, onlyOnce) {
  41803. this.frame = frame;
  41804. this.action = action;
  41805. this.onlyOnce = onlyOnce;
  41806. this.isDone = false;
  41807. }
  41808. return AnimationEvent;
  41809. }());
  41810. BABYLON.AnimationEvent = AnimationEvent;
  41811. var PathCursor = /** @class */ (function () {
  41812. function PathCursor(path) {
  41813. this.path = path;
  41814. this._onchange = new Array();
  41815. this.value = 0;
  41816. this.animations = new Array();
  41817. }
  41818. PathCursor.prototype.getPoint = function () {
  41819. var point = this.path.getPointAtLengthPosition(this.value);
  41820. return new BABYLON.Vector3(point.x, 0, point.y);
  41821. };
  41822. PathCursor.prototype.moveAhead = function (step) {
  41823. if (step === void 0) { step = 0.002; }
  41824. this.move(step);
  41825. return this;
  41826. };
  41827. PathCursor.prototype.moveBack = function (step) {
  41828. if (step === void 0) { step = 0.002; }
  41829. this.move(-step);
  41830. return this;
  41831. };
  41832. PathCursor.prototype.move = function (step) {
  41833. if (Math.abs(step) > 1) {
  41834. throw "step size should be less than 1.";
  41835. }
  41836. this.value += step;
  41837. this.ensureLimits();
  41838. this.raiseOnChange();
  41839. return this;
  41840. };
  41841. PathCursor.prototype.ensureLimits = function () {
  41842. while (this.value > 1) {
  41843. this.value -= 1;
  41844. }
  41845. while (this.value < 0) {
  41846. this.value += 1;
  41847. }
  41848. return this;
  41849. };
  41850. // used by animation engine
  41851. PathCursor.prototype.raiseOnChange = function () {
  41852. var _this = this;
  41853. this._onchange.forEach(function (f) { return f(_this); });
  41854. return this;
  41855. };
  41856. PathCursor.prototype.onchange = function (f) {
  41857. this._onchange.push(f);
  41858. return this;
  41859. };
  41860. return PathCursor;
  41861. }());
  41862. BABYLON.PathCursor = PathCursor;
  41863. var AnimationKeyInterpolation;
  41864. (function (AnimationKeyInterpolation) {
  41865. /**
  41866. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  41867. */
  41868. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  41869. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  41870. var Animation = /** @class */ (function () {
  41871. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  41872. this.name = name;
  41873. this.targetProperty = targetProperty;
  41874. this.framePerSecond = framePerSecond;
  41875. this.dataType = dataType;
  41876. this.loopMode = loopMode;
  41877. this.enableBlending = enableBlending;
  41878. this._runtimeAnimations = new Array();
  41879. // The set of event that will be linked to this animation
  41880. this._events = new Array();
  41881. this.blendingSpeed = 0.01;
  41882. this._ranges = {};
  41883. this.targetPropertyPath = targetProperty.split(".");
  41884. this.dataType = dataType;
  41885. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  41886. }
  41887. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  41888. var dataType = undefined;
  41889. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  41890. dataType = Animation.ANIMATIONTYPE_FLOAT;
  41891. }
  41892. else if (from instanceof BABYLON.Quaternion) {
  41893. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  41894. }
  41895. else if (from instanceof BABYLON.Vector3) {
  41896. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  41897. }
  41898. else if (from instanceof BABYLON.Vector2) {
  41899. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  41900. }
  41901. else if (from instanceof BABYLON.Color3) {
  41902. dataType = Animation.ANIMATIONTYPE_COLOR3;
  41903. }
  41904. else if (from instanceof BABYLON.Size) {
  41905. dataType = Animation.ANIMATIONTYPE_SIZE;
  41906. }
  41907. if (dataType == undefined) {
  41908. return null;
  41909. }
  41910. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  41911. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  41912. animation.setKeys(keys);
  41913. if (easingFunction !== undefined) {
  41914. animation.setEasingFunction(easingFunction);
  41915. }
  41916. return animation;
  41917. };
  41918. /**
  41919. * Sets up an animation.
  41920. * @param property the property to animate
  41921. * @param animationType the animation type to apply
  41922. * @param easingFunction the easing function used in the animation
  41923. * @returns The created animation
  41924. */
  41925. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  41926. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  41927. animation.setEasingFunction(easingFunction);
  41928. return animation;
  41929. };
  41930. /**
  41931. * Create and start an animation on a node
  41932. * @param {string} name defines the name of the global animation that will be run on all nodes
  41933. * @param {BABYLON.Node} node defines the root node where the animation will take place
  41934. * @param {string} targetProperty defines property to animate
  41935. * @param {number} framePerSecond defines the number of frame per second yo use
  41936. * @param {number} totalFrame defines the number of frames in total
  41937. * @param {any} from defines the initial value
  41938. * @param {any} to defines the final value
  41939. * @param {number} loopMode defines which loop mode you want to use (off by default)
  41940. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  41941. * @param onAnimationEnd defines the callback to call when animation end
  41942. * @returns the animatable created for this animation
  41943. */
  41944. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41945. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41946. if (!animation) {
  41947. return null;
  41948. }
  41949. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41950. };
  41951. /**
  41952. * Create and start an animation on a node and its descendants
  41953. * @param {string} name defines the name of the global animation that will be run on all nodes
  41954. * @param {BABYLON.Node} node defines the root node where the animation will take place
  41955. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  41956. * @param {string} targetProperty defines property to animate
  41957. * @param {number} framePerSecond defines the number of frame per second yo use
  41958. * @param {number} totalFrame defines the number of frames in total
  41959. * @param {any} from defines the initial value
  41960. * @param {any} to defines the final value
  41961. * @param {number} loopMode defines which loop mode you want to use (off by default)
  41962. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  41963. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  41964. * @returns the list of animatables created for all nodes
  41965. * @example https://www.babylonjs-playground.com/#MH0VLI
  41966. */
  41967. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41968. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41969. if (!animation) {
  41970. return null;
  41971. }
  41972. var scene = node.getScene();
  41973. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41974. };
  41975. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41976. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41977. if (!animation) {
  41978. return null;
  41979. }
  41980. node.animations.push(animation);
  41981. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41982. };
  41983. /**
  41984. * Transition property of the Camera to the target Value.
  41985. * @param property The property to transition
  41986. * @param targetValue The target Value of the property
  41987. * @param host The object where the property to animate belongs
  41988. * @param scene Scene used to run the animation
  41989. * @param frameRate Framerate (in frame/s) to use
  41990. * @param transition The transition type we want to use
  41991. * @param duration The duration of the animation, in milliseconds
  41992. * @param onAnimationEnd Call back trigger at the end of the animation.
  41993. */
  41994. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  41995. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  41996. if (duration <= 0) {
  41997. host[property] = targetValue;
  41998. if (onAnimationEnd) {
  41999. onAnimationEnd();
  42000. }
  42001. return null;
  42002. }
  42003. var endFrame = frameRate * (duration / 1000);
  42004. transition.setKeys([{
  42005. frame: 0,
  42006. value: host[property].clone ? host[property].clone() : host[property]
  42007. },
  42008. {
  42009. frame: endFrame,
  42010. value: targetValue
  42011. }]);
  42012. if (!host.animations) {
  42013. host.animations = [];
  42014. }
  42015. host.animations.push(transition);
  42016. var animation = scene.beginAnimation(host, 0, endFrame, false);
  42017. animation.onAnimationEnd = onAnimationEnd;
  42018. return animation;
  42019. };
  42020. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  42021. /**
  42022. * Return the array of runtime animations currently using this animation
  42023. */
  42024. get: function () {
  42025. return this._runtimeAnimations;
  42026. },
  42027. enumerable: true,
  42028. configurable: true
  42029. });
  42030. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  42031. get: function () {
  42032. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  42033. var runtimeAnimation = _a[_i];
  42034. if (!runtimeAnimation.isStopped) {
  42035. return true;
  42036. }
  42037. }
  42038. return false;
  42039. },
  42040. enumerable: true,
  42041. configurable: true
  42042. });
  42043. // Methods
  42044. /**
  42045. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  42046. */
  42047. Animation.prototype.toString = function (fullDetails) {
  42048. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  42049. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  42050. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  42051. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  42052. if (fullDetails) {
  42053. ret += ", Ranges: {";
  42054. var first = true;
  42055. for (var name in this._ranges) {
  42056. if (first) {
  42057. ret += ", ";
  42058. first = false;
  42059. }
  42060. ret += name;
  42061. }
  42062. ret += "}";
  42063. }
  42064. return ret;
  42065. };
  42066. /**
  42067. * Add an event to this animation.
  42068. */
  42069. Animation.prototype.addEvent = function (event) {
  42070. this._events.push(event);
  42071. };
  42072. /**
  42073. * Remove all events found at the given frame
  42074. * @param frame
  42075. */
  42076. Animation.prototype.removeEvents = function (frame) {
  42077. for (var index = 0; index < this._events.length; index++) {
  42078. if (this._events[index].frame === frame) {
  42079. this._events.splice(index, 1);
  42080. index--;
  42081. }
  42082. }
  42083. };
  42084. Animation.prototype.getEvents = function () {
  42085. return this._events;
  42086. };
  42087. Animation.prototype.createRange = function (name, from, to) {
  42088. // check name not already in use; could happen for bones after serialized
  42089. if (!this._ranges[name]) {
  42090. this._ranges[name] = new AnimationRange(name, from, to);
  42091. }
  42092. };
  42093. Animation.prototype.deleteRange = function (name, deleteFrames) {
  42094. if (deleteFrames === void 0) { deleteFrames = true; }
  42095. var range = this._ranges[name];
  42096. if (!range) {
  42097. return;
  42098. }
  42099. if (deleteFrames) {
  42100. var from = range.from;
  42101. var to = range.to;
  42102. // this loop MUST go high to low for multiple splices to work
  42103. for (var key = this._keys.length - 1; key >= 0; key--) {
  42104. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  42105. this._keys.splice(key, 1);
  42106. }
  42107. }
  42108. }
  42109. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  42110. };
  42111. Animation.prototype.getRange = function (name) {
  42112. return this._ranges[name];
  42113. };
  42114. Animation.prototype.getKeys = function () {
  42115. return this._keys;
  42116. };
  42117. Animation.prototype.getHighestFrame = function () {
  42118. var ret = 0;
  42119. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  42120. if (ret < this._keys[key].frame) {
  42121. ret = this._keys[key].frame;
  42122. }
  42123. }
  42124. return ret;
  42125. };
  42126. Animation.prototype.getEasingFunction = function () {
  42127. return this._easingFunction;
  42128. };
  42129. Animation.prototype.setEasingFunction = function (easingFunction) {
  42130. this._easingFunction = easingFunction;
  42131. };
  42132. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  42133. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  42134. };
  42135. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42136. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42137. };
  42138. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  42139. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  42140. };
  42141. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42142. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  42143. };
  42144. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  42145. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  42146. };
  42147. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42148. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42149. };
  42150. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  42151. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  42152. };
  42153. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42154. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42155. };
  42156. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  42157. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  42158. };
  42159. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  42160. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  42161. };
  42162. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  42163. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  42164. };
  42165. Animation.prototype.clone = function () {
  42166. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  42167. clone.enableBlending = this.enableBlending;
  42168. clone.blendingSpeed = this.blendingSpeed;
  42169. if (this._keys) {
  42170. clone.setKeys(this._keys);
  42171. }
  42172. if (this._ranges) {
  42173. clone._ranges = {};
  42174. for (var name in this._ranges) {
  42175. var range = this._ranges[name];
  42176. if (!range) {
  42177. continue;
  42178. }
  42179. clone._ranges[name] = range.clone();
  42180. }
  42181. }
  42182. return clone;
  42183. };
  42184. Animation.prototype.setKeys = function (values) {
  42185. this._keys = values.slice(0);
  42186. };
  42187. Animation.prototype.serialize = function () {
  42188. var serializationObject = {};
  42189. serializationObject.name = this.name;
  42190. serializationObject.property = this.targetProperty;
  42191. serializationObject.framePerSecond = this.framePerSecond;
  42192. serializationObject.dataType = this.dataType;
  42193. serializationObject.loopBehavior = this.loopMode;
  42194. serializationObject.enableBlending = this.enableBlending;
  42195. serializationObject.blendingSpeed = this.blendingSpeed;
  42196. var dataType = this.dataType;
  42197. serializationObject.keys = [];
  42198. var keys = this.getKeys();
  42199. for (var index = 0; index < keys.length; index++) {
  42200. var animationKey = keys[index];
  42201. var key = {};
  42202. key.frame = animationKey.frame;
  42203. switch (dataType) {
  42204. case Animation.ANIMATIONTYPE_FLOAT:
  42205. key.values = [animationKey.value];
  42206. break;
  42207. case Animation.ANIMATIONTYPE_QUATERNION:
  42208. case Animation.ANIMATIONTYPE_MATRIX:
  42209. case Animation.ANIMATIONTYPE_VECTOR3:
  42210. case Animation.ANIMATIONTYPE_COLOR3:
  42211. key.values = animationKey.value.asArray();
  42212. break;
  42213. }
  42214. serializationObject.keys.push(key);
  42215. }
  42216. serializationObject.ranges = [];
  42217. for (var name in this._ranges) {
  42218. var source = this._ranges[name];
  42219. if (!source) {
  42220. continue;
  42221. }
  42222. var range = {};
  42223. range.name = name;
  42224. range.from = source.from;
  42225. range.to = source.to;
  42226. serializationObject.ranges.push(range);
  42227. }
  42228. return serializationObject;
  42229. };
  42230. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  42231. get: function () {
  42232. return Animation._ANIMATIONTYPE_FLOAT;
  42233. },
  42234. enumerable: true,
  42235. configurable: true
  42236. });
  42237. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  42238. get: function () {
  42239. return Animation._ANIMATIONTYPE_VECTOR3;
  42240. },
  42241. enumerable: true,
  42242. configurable: true
  42243. });
  42244. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  42245. get: function () {
  42246. return Animation._ANIMATIONTYPE_VECTOR2;
  42247. },
  42248. enumerable: true,
  42249. configurable: true
  42250. });
  42251. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  42252. get: function () {
  42253. return Animation._ANIMATIONTYPE_SIZE;
  42254. },
  42255. enumerable: true,
  42256. configurable: true
  42257. });
  42258. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  42259. get: function () {
  42260. return Animation._ANIMATIONTYPE_QUATERNION;
  42261. },
  42262. enumerable: true,
  42263. configurable: true
  42264. });
  42265. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  42266. get: function () {
  42267. return Animation._ANIMATIONTYPE_MATRIX;
  42268. },
  42269. enumerable: true,
  42270. configurable: true
  42271. });
  42272. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  42273. get: function () {
  42274. return Animation._ANIMATIONTYPE_COLOR3;
  42275. },
  42276. enumerable: true,
  42277. configurable: true
  42278. });
  42279. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  42280. get: function () {
  42281. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  42282. },
  42283. enumerable: true,
  42284. configurable: true
  42285. });
  42286. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  42287. get: function () {
  42288. return Animation._ANIMATIONLOOPMODE_CYCLE;
  42289. },
  42290. enumerable: true,
  42291. configurable: true
  42292. });
  42293. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  42294. get: function () {
  42295. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  42296. },
  42297. enumerable: true,
  42298. configurable: true
  42299. });
  42300. Animation.Parse = function (parsedAnimation) {
  42301. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  42302. var dataType = parsedAnimation.dataType;
  42303. var keys = [];
  42304. var data;
  42305. var index;
  42306. if (parsedAnimation.enableBlending) {
  42307. animation.enableBlending = parsedAnimation.enableBlending;
  42308. }
  42309. if (parsedAnimation.blendingSpeed) {
  42310. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  42311. }
  42312. for (index = 0; index < parsedAnimation.keys.length; index++) {
  42313. var key = parsedAnimation.keys[index];
  42314. var inTangent;
  42315. var outTangent;
  42316. switch (dataType) {
  42317. case Animation.ANIMATIONTYPE_FLOAT:
  42318. data = key.values[0];
  42319. if (key.values.length >= 1) {
  42320. inTangent = key.values[1];
  42321. }
  42322. if (key.values.length >= 2) {
  42323. outTangent = key.values[2];
  42324. }
  42325. break;
  42326. case Animation.ANIMATIONTYPE_QUATERNION:
  42327. data = BABYLON.Quaternion.FromArray(key.values);
  42328. if (key.values.length >= 8) {
  42329. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  42330. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  42331. inTangent = _inTangent;
  42332. }
  42333. }
  42334. if (key.values.length >= 12) {
  42335. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  42336. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  42337. outTangent = _outTangent;
  42338. }
  42339. }
  42340. break;
  42341. case Animation.ANIMATIONTYPE_MATRIX:
  42342. data = BABYLON.Matrix.FromArray(key.values);
  42343. break;
  42344. case Animation.ANIMATIONTYPE_COLOR3:
  42345. data = BABYLON.Color3.FromArray(key.values);
  42346. break;
  42347. case Animation.ANIMATIONTYPE_VECTOR3:
  42348. default:
  42349. data = BABYLON.Vector3.FromArray(key.values);
  42350. break;
  42351. }
  42352. var keyData = {};
  42353. keyData.frame = key.frame;
  42354. keyData.value = data;
  42355. if (inTangent != undefined) {
  42356. keyData.inTangent = inTangent;
  42357. }
  42358. if (outTangent != undefined) {
  42359. keyData.outTangent = outTangent;
  42360. }
  42361. keys.push(keyData);
  42362. }
  42363. animation.setKeys(keys);
  42364. if (parsedAnimation.ranges) {
  42365. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  42366. data = parsedAnimation.ranges[index];
  42367. animation.createRange(data.name, data.from, data.to);
  42368. }
  42369. }
  42370. return animation;
  42371. };
  42372. Animation.AppendSerializedAnimations = function (source, destination) {
  42373. if (source.animations) {
  42374. destination.animations = [];
  42375. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  42376. var animation = source.animations[animationIndex];
  42377. destination.animations.push(animation.serialize());
  42378. }
  42379. }
  42380. };
  42381. Animation.AllowMatricesInterpolation = false;
  42382. // Statics
  42383. Animation._ANIMATIONTYPE_FLOAT = 0;
  42384. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  42385. Animation._ANIMATIONTYPE_QUATERNION = 2;
  42386. Animation._ANIMATIONTYPE_MATRIX = 3;
  42387. Animation._ANIMATIONTYPE_COLOR3 = 4;
  42388. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  42389. Animation._ANIMATIONTYPE_SIZE = 6;
  42390. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  42391. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  42392. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  42393. return Animation;
  42394. }());
  42395. BABYLON.Animation = Animation;
  42396. })(BABYLON || (BABYLON = {}));
  42397. //# sourceMappingURL=babylon.animation.js.map
  42398. var BABYLON;
  42399. (function (BABYLON) {
  42400. /**
  42401. * This class defines the direct association between an animation and a target
  42402. */
  42403. var TargetedAnimation = /** @class */ (function () {
  42404. function TargetedAnimation() {
  42405. }
  42406. return TargetedAnimation;
  42407. }());
  42408. BABYLON.TargetedAnimation = TargetedAnimation;
  42409. /**
  42410. * Use this class to create coordinated animations on multiple targets
  42411. */
  42412. var AnimationGroup = /** @class */ (function () {
  42413. function AnimationGroup(name, scene) {
  42414. if (scene === void 0) { scene = null; }
  42415. this.name = name;
  42416. this._targetedAnimations = new Array();
  42417. this._animatables = new Array();
  42418. this._from = Number.MAX_VALUE;
  42419. this._to = -Number.MAX_VALUE;
  42420. this._speedRatio = 1;
  42421. this.onAnimationEndObservable = new BABYLON.Observable();
  42422. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  42423. this._scene.animationGroups.push(this);
  42424. }
  42425. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  42426. /**
  42427. * Define if the animations are started
  42428. */
  42429. get: function () {
  42430. return this._isStarted;
  42431. },
  42432. enumerable: true,
  42433. configurable: true
  42434. });
  42435. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  42436. /**
  42437. * Gets or sets the speed ratio to use for all animations
  42438. */
  42439. get: function () {
  42440. return this._speedRatio;
  42441. },
  42442. /**
  42443. * Gets or sets the speed ratio to use for all animations
  42444. */
  42445. set: function (value) {
  42446. if (this._speedRatio === value) {
  42447. return;
  42448. }
  42449. this._speedRatio = value;
  42450. for (var index = 0; index < this._animatables.length; index++) {
  42451. var animatable = this._animatables[index];
  42452. animatable.speedRatio = this._speedRatio;
  42453. }
  42454. },
  42455. enumerable: true,
  42456. configurable: true
  42457. });
  42458. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  42459. /**
  42460. * Gets the targeted animations for this animation group
  42461. */
  42462. get: function () {
  42463. return this._targetedAnimations;
  42464. },
  42465. enumerable: true,
  42466. configurable: true
  42467. });
  42468. /**
  42469. * Add an animation (with its target) in the group
  42470. * @param animation defines the animation we want to add
  42471. * @param target defines the target of the animation
  42472. * @returns the {BABYLON.TargetedAnimation} object
  42473. */
  42474. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  42475. var targetedAnimation = {
  42476. animation: animation,
  42477. target: target
  42478. };
  42479. var keys = animation.getKeys();
  42480. if (this._from > keys[0].frame) {
  42481. this._from = keys[0].frame;
  42482. }
  42483. if (this._to < keys[keys.length - 1].frame) {
  42484. this._to = keys[keys.length - 1].frame;
  42485. }
  42486. this._targetedAnimations.push(targetedAnimation);
  42487. return targetedAnimation;
  42488. };
  42489. /**
  42490. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  42491. * It can add constant keys at begin or end
  42492. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  42493. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  42494. */
  42495. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  42496. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  42497. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  42498. beginFrame = Math.max(beginFrame, this._from);
  42499. endFrame = Math.min(endFrame, this._to);
  42500. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42501. var targetedAnimation = this._targetedAnimations[index];
  42502. var keys = targetedAnimation.animation.getKeys();
  42503. var startKey = keys[0];
  42504. var endKey = keys[keys.length - 1];
  42505. if (startKey.frame > beginFrame) {
  42506. var newKey = {
  42507. frame: beginFrame,
  42508. value: startKey.value,
  42509. inTangent: startKey.inTangent,
  42510. outTangent: startKey.outTangent,
  42511. interpolation: startKey.interpolation
  42512. };
  42513. keys.splice(0, 0, newKey);
  42514. }
  42515. if (endKey.frame < endFrame) {
  42516. var newKey = {
  42517. frame: endFrame,
  42518. value: endKey.value,
  42519. inTangent: endKey.outTangent,
  42520. outTangent: endKey.outTangent,
  42521. interpolation: endKey.interpolation
  42522. };
  42523. keys.push(newKey);
  42524. }
  42525. }
  42526. return this;
  42527. };
  42528. /**
  42529. * Start all animations on given targets
  42530. * @param loop defines if animations must loop
  42531. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  42532. */
  42533. AnimationGroup.prototype.start = function (loop, speedRatio) {
  42534. var _this = this;
  42535. if (loop === void 0) { loop = false; }
  42536. if (speedRatio === void 0) { speedRatio = 1; }
  42537. if (this._isStarted || this._targetedAnimations.length === 0) {
  42538. return this;
  42539. }
  42540. var _loop_1 = function () {
  42541. var targetedAnimation = this_1._targetedAnimations[index];
  42542. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  42543. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  42544. }));
  42545. };
  42546. var this_1 = this;
  42547. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42548. _loop_1();
  42549. }
  42550. this._speedRatio = speedRatio;
  42551. this._isStarted = true;
  42552. return this;
  42553. };
  42554. /**
  42555. * Pause all animations
  42556. */
  42557. AnimationGroup.prototype.pause = function () {
  42558. if (!this._isStarted) {
  42559. return this;
  42560. }
  42561. for (var index = 0; index < this._animatables.length; index++) {
  42562. var animatable = this._animatables[index];
  42563. animatable.pause();
  42564. }
  42565. return this;
  42566. };
  42567. /**
  42568. * Play all animations to initial state
  42569. * This function will start() the animations if they were not started or will restart() them if they were paused
  42570. * @param loop defines if animations must loop
  42571. */
  42572. AnimationGroup.prototype.play = function (loop) {
  42573. if (this.isStarted) {
  42574. if (loop !== undefined) {
  42575. for (var index = 0; index < this._animatables.length; index++) {
  42576. var animatable = this._animatables[index];
  42577. animatable.loopAnimation = loop;
  42578. }
  42579. }
  42580. this.restart();
  42581. }
  42582. else {
  42583. this.start(loop, this._speedRatio);
  42584. }
  42585. return this;
  42586. };
  42587. /**
  42588. * Reset all animations to initial state
  42589. */
  42590. AnimationGroup.prototype.reset = function () {
  42591. if (!this._isStarted) {
  42592. return this;
  42593. }
  42594. for (var index = 0; index < this._animatables.length; index++) {
  42595. var animatable = this._animatables[index];
  42596. animatable.reset();
  42597. }
  42598. return this;
  42599. };
  42600. /**
  42601. * Restart animations from key 0
  42602. */
  42603. AnimationGroup.prototype.restart = function () {
  42604. if (!this._isStarted) {
  42605. return this;
  42606. }
  42607. for (var index = 0; index < this._animatables.length; index++) {
  42608. var animatable = this._animatables[index];
  42609. animatable.restart();
  42610. }
  42611. return this;
  42612. };
  42613. /**
  42614. * Stop all animations
  42615. */
  42616. AnimationGroup.prototype.stop = function () {
  42617. if (!this._isStarted) {
  42618. return this;
  42619. }
  42620. for (var index = 0; index < this._animatables.length; index++) {
  42621. var animatable = this._animatables[index];
  42622. animatable.stop();
  42623. }
  42624. this._isStarted = false;
  42625. return this;
  42626. };
  42627. /**
  42628. * Dispose all associated resources
  42629. */
  42630. AnimationGroup.prototype.dispose = function () {
  42631. this._targetedAnimations = [];
  42632. this._animatables = [];
  42633. var index = this._scene.animationGroups.indexOf(this);
  42634. if (index > -1) {
  42635. this._scene.animationGroups.splice(index, 1);
  42636. }
  42637. };
  42638. return AnimationGroup;
  42639. }());
  42640. BABYLON.AnimationGroup = AnimationGroup;
  42641. })(BABYLON || (BABYLON = {}));
  42642. //# sourceMappingURL=babylon.animationGroup.js.map
  42643. var BABYLON;
  42644. (function (BABYLON) {
  42645. var RuntimeAnimation = /** @class */ (function () {
  42646. function RuntimeAnimation(target, animation) {
  42647. this._offsetsCache = {};
  42648. this._highLimitsCache = {};
  42649. this._stopped = false;
  42650. this._blendingFactor = 0;
  42651. this._ratioOffset = 0;
  42652. this._animation = animation;
  42653. this._target = target;
  42654. animation._runtimeAnimations.push(this);
  42655. }
  42656. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  42657. get: function () {
  42658. return this._animation;
  42659. },
  42660. enumerable: true,
  42661. configurable: true
  42662. });
  42663. RuntimeAnimation.prototype.reset = function () {
  42664. this._offsetsCache = {};
  42665. this._highLimitsCache = {};
  42666. this.currentFrame = 0;
  42667. this._blendingFactor = 0;
  42668. this._originalBlendValue = null;
  42669. };
  42670. RuntimeAnimation.prototype.isStopped = function () {
  42671. return this._stopped;
  42672. };
  42673. RuntimeAnimation.prototype.dispose = function () {
  42674. var index = this._animation.runtimeAnimations.indexOf(this);
  42675. if (index > -1) {
  42676. this._animation.runtimeAnimations.splice(index, 1);
  42677. }
  42678. };
  42679. RuntimeAnimation.prototype._getKeyValue = function (value) {
  42680. if (typeof value === "function") {
  42681. return value();
  42682. }
  42683. return value;
  42684. };
  42685. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  42686. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  42687. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  42688. }
  42689. this.currentFrame = currentFrame;
  42690. var keys = this._animation.getKeys();
  42691. // Try to get a hash to find the right key
  42692. 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));
  42693. if (keys[startKeyIndex].frame >= currentFrame) {
  42694. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  42695. startKeyIndex--;
  42696. }
  42697. }
  42698. for (var key = startKeyIndex; key < keys.length; key++) {
  42699. var endKey = keys[key + 1];
  42700. if (endKey.frame >= currentFrame) {
  42701. var startKey = keys[key];
  42702. var startValue = this._getKeyValue(startKey.value);
  42703. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  42704. return startValue;
  42705. }
  42706. var endValue = this._getKeyValue(endKey.value);
  42707. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  42708. var frameDelta = endKey.frame - startKey.frame;
  42709. // gradient : percent of currentFrame between the frame inf and the frame sup
  42710. var gradient = (currentFrame - startKey.frame) / frameDelta;
  42711. // check for easingFunction and correction of gradient
  42712. var easingFunction = this._animation.getEasingFunction();
  42713. if (easingFunction != null) {
  42714. gradient = easingFunction.ease(gradient);
  42715. }
  42716. switch (this._animation.dataType) {
  42717. // Float
  42718. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42719. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  42720. switch (loopMode) {
  42721. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42722. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42723. return floatValue;
  42724. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42725. return offsetValue * repeatCount + floatValue;
  42726. }
  42727. break;
  42728. // Quaternion
  42729. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42730. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  42731. switch (loopMode) {
  42732. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42733. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42734. return quatValue;
  42735. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42736. return quatValue.add(offsetValue.scale(repeatCount));
  42737. }
  42738. return quatValue;
  42739. // Vector3
  42740. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42741. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  42742. switch (loopMode) {
  42743. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42744. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42745. return vec3Value;
  42746. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42747. return vec3Value.add(offsetValue.scale(repeatCount));
  42748. }
  42749. // Vector2
  42750. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42751. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  42752. switch (loopMode) {
  42753. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42754. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42755. return vec2Value;
  42756. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42757. return vec2Value.add(offsetValue.scale(repeatCount));
  42758. }
  42759. // Size
  42760. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42761. switch (loopMode) {
  42762. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42763. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42764. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  42765. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42766. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42767. }
  42768. // Color3
  42769. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42770. switch (loopMode) {
  42771. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42772. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42773. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  42774. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42775. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42776. }
  42777. // Matrix
  42778. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  42779. switch (loopMode) {
  42780. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42781. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42782. if (BABYLON.Animation.AllowMatricesInterpolation) {
  42783. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  42784. }
  42785. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42786. return startValue;
  42787. }
  42788. default:
  42789. break;
  42790. }
  42791. break;
  42792. }
  42793. }
  42794. return this._getKeyValue(keys[keys.length - 1].value);
  42795. };
  42796. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  42797. if (blend === void 0) { blend = false; }
  42798. // Set value
  42799. var path;
  42800. var destination;
  42801. var targetPropertyPath = this._animation.targetPropertyPath;
  42802. if (targetPropertyPath.length > 1) {
  42803. var property = this._target[targetPropertyPath[0]];
  42804. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  42805. property = property[targetPropertyPath[index]];
  42806. }
  42807. path = targetPropertyPath[targetPropertyPath.length - 1];
  42808. destination = property;
  42809. }
  42810. else {
  42811. path = targetPropertyPath[0];
  42812. destination = this._target;
  42813. }
  42814. // Blending
  42815. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  42816. if (!this._originalBlendValue) {
  42817. if (destination[path].clone) {
  42818. this._originalBlendValue = destination[path].clone();
  42819. }
  42820. else {
  42821. this._originalBlendValue = destination[path];
  42822. }
  42823. }
  42824. if (this._originalBlendValue.prototype) {
  42825. if (this._originalBlendValue.prototype.Lerp) {
  42826. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  42827. }
  42828. else {
  42829. destination[path] = currentValue;
  42830. }
  42831. }
  42832. else if (this._originalBlendValue.m) {
  42833. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  42834. }
  42835. else {
  42836. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  42837. }
  42838. this._blendingFactor += this._animation.blendingSpeed;
  42839. }
  42840. else {
  42841. destination[path] = currentValue;
  42842. }
  42843. if (this._target.markAsDirty) {
  42844. this._target.markAsDirty(this._animation.targetProperty);
  42845. }
  42846. };
  42847. RuntimeAnimation.prototype.goToFrame = function (frame) {
  42848. var keys = this._animation.getKeys();
  42849. if (frame < keys[0].frame) {
  42850. frame = keys[0].frame;
  42851. }
  42852. else if (frame > keys[keys.length - 1].frame) {
  42853. frame = keys[keys.length - 1].frame;
  42854. }
  42855. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  42856. this.setValue(currentValue);
  42857. };
  42858. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  42859. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  42860. this._ratioOffset = this._previousRatio - newRatio;
  42861. };
  42862. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  42863. if (blend === void 0) { blend = false; }
  42864. var targetPropertyPath = this._animation.targetPropertyPath;
  42865. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  42866. this._stopped = true;
  42867. return false;
  42868. }
  42869. var returnValue = true;
  42870. var keys = this._animation.getKeys();
  42871. // Adding a start key at frame 0 if missing
  42872. if (keys[0].frame !== 0) {
  42873. var newKey = { frame: 0, value: keys[0].value };
  42874. keys.splice(0, 0, newKey);
  42875. }
  42876. // Check limits
  42877. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  42878. from = keys[0].frame;
  42879. }
  42880. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  42881. to = keys[keys.length - 1].frame;
  42882. }
  42883. //to and from cannot be the same key
  42884. if (from === to) {
  42885. if (from > keys[0].frame) {
  42886. from--;
  42887. }
  42888. else if (to < keys[keys.length - 1].frame) {
  42889. to++;
  42890. }
  42891. }
  42892. // Compute ratio
  42893. var range = to - from;
  42894. var offsetValue;
  42895. // ratio represents the frame delta between from and to
  42896. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  42897. var highLimitValue = 0;
  42898. this._previousDelay = delay;
  42899. this._previousRatio = ratio;
  42900. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  42901. returnValue = false;
  42902. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  42903. }
  42904. else {
  42905. // Get max value if required
  42906. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  42907. var keyOffset = to.toString() + from.toString();
  42908. if (!this._offsetsCache[keyOffset]) {
  42909. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42910. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42911. switch (this._animation.dataType) {
  42912. // Float
  42913. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42914. this._offsetsCache[keyOffset] = toValue - fromValue;
  42915. break;
  42916. // Quaternion
  42917. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42918. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42919. break;
  42920. // Vector3
  42921. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42922. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42923. // Vector2
  42924. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42925. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42926. // Size
  42927. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42928. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42929. // Color3
  42930. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42931. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42932. default:
  42933. break;
  42934. }
  42935. this._highLimitsCache[keyOffset] = toValue;
  42936. }
  42937. highLimitValue = this._highLimitsCache[keyOffset];
  42938. offsetValue = this._offsetsCache[keyOffset];
  42939. }
  42940. }
  42941. if (offsetValue === undefined) {
  42942. switch (this._animation.dataType) {
  42943. // Float
  42944. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42945. offsetValue = 0;
  42946. break;
  42947. // Quaternion
  42948. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42949. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  42950. break;
  42951. // Vector3
  42952. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42953. offsetValue = BABYLON.Vector3.Zero();
  42954. break;
  42955. // Vector2
  42956. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42957. offsetValue = BABYLON.Vector2.Zero();
  42958. break;
  42959. // Size
  42960. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42961. offsetValue = BABYLON.Size.Zero();
  42962. break;
  42963. // Color3
  42964. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42965. offsetValue = BABYLON.Color3.Black();
  42966. }
  42967. }
  42968. // Compute value
  42969. var repeatCount = (ratio / range) >> 0;
  42970. var currentFrame = returnValue ? from + ratio % range : to;
  42971. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  42972. // Set value
  42973. this.setValue(currentValue);
  42974. // Check events
  42975. var events = this._animation.getEvents();
  42976. for (var index = 0; index < events.length; index++) {
  42977. // Make sure current frame has passed event frame and that event frame is within the current range
  42978. // Also, handle both forward and reverse animations
  42979. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  42980. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  42981. var event = events[index];
  42982. if (!event.isDone) {
  42983. // If event should be done only once, remove it.
  42984. if (event.onlyOnce) {
  42985. events.splice(index, 1);
  42986. index--;
  42987. }
  42988. event.isDone = true;
  42989. event.action();
  42990. } // Don't do anything if the event has already be done.
  42991. }
  42992. else if (events[index].isDone && !events[index].onlyOnce) {
  42993. // reset event, the animation is looping
  42994. events[index].isDone = false;
  42995. }
  42996. }
  42997. if (!returnValue) {
  42998. this._stopped = true;
  42999. }
  43000. return returnValue;
  43001. };
  43002. return RuntimeAnimation;
  43003. }());
  43004. BABYLON.RuntimeAnimation = RuntimeAnimation;
  43005. })(BABYLON || (BABYLON = {}));
  43006. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  43007. var BABYLON;
  43008. (function (BABYLON) {
  43009. var Animatable = /** @class */ (function () {
  43010. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  43011. if (fromFrame === void 0) { fromFrame = 0; }
  43012. if (toFrame === void 0) { toFrame = 100; }
  43013. if (loopAnimation === void 0) { loopAnimation = false; }
  43014. if (speedRatio === void 0) { speedRatio = 1.0; }
  43015. this.target = target;
  43016. this.fromFrame = fromFrame;
  43017. this.toFrame = toFrame;
  43018. this.loopAnimation = loopAnimation;
  43019. this.onAnimationEnd = onAnimationEnd;
  43020. this._localDelayOffset = null;
  43021. this._pausedDelay = null;
  43022. this._runtimeAnimations = new Array();
  43023. this._paused = false;
  43024. this._speedRatio = 1;
  43025. this.animationStarted = false;
  43026. if (animations) {
  43027. this.appendAnimations(target, animations);
  43028. }
  43029. this._speedRatio = speedRatio;
  43030. this._scene = scene;
  43031. scene._activeAnimatables.push(this);
  43032. }
  43033. Object.defineProperty(Animatable.prototype, "speedRatio", {
  43034. get: function () {
  43035. return this._speedRatio;
  43036. },
  43037. set: function (value) {
  43038. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  43039. var animation = this._runtimeAnimations[index];
  43040. animation._prepareForSpeedRatioChange(value);
  43041. }
  43042. this._speedRatio = value;
  43043. },
  43044. enumerable: true,
  43045. configurable: true
  43046. });
  43047. // Methods
  43048. Animatable.prototype.getAnimations = function () {
  43049. return this._runtimeAnimations;
  43050. };
  43051. Animatable.prototype.appendAnimations = function (target, animations) {
  43052. for (var index = 0; index < animations.length; index++) {
  43053. var animation = animations[index];
  43054. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  43055. }
  43056. };
  43057. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  43058. var runtimeAnimations = this._runtimeAnimations;
  43059. for (var index = 0; index < runtimeAnimations.length; index++) {
  43060. if (runtimeAnimations[index].animation.targetProperty === property) {
  43061. return runtimeAnimations[index].animation;
  43062. }
  43063. }
  43064. return null;
  43065. };
  43066. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  43067. var runtimeAnimations = this._runtimeAnimations;
  43068. for (var index = 0; index < runtimeAnimations.length; index++) {
  43069. if (runtimeAnimations[index].animation.targetProperty === property) {
  43070. return runtimeAnimations[index];
  43071. }
  43072. }
  43073. return null;
  43074. };
  43075. Animatable.prototype.reset = function () {
  43076. var runtimeAnimations = this._runtimeAnimations;
  43077. for (var index = 0; index < runtimeAnimations.length; index++) {
  43078. runtimeAnimations[index].reset();
  43079. }
  43080. // Reset to original value
  43081. for (index = 0; index < runtimeAnimations.length; index++) {
  43082. var animation = runtimeAnimations[index];
  43083. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  43084. }
  43085. this._localDelayOffset = null;
  43086. this._pausedDelay = null;
  43087. };
  43088. Animatable.prototype.enableBlending = function (blendingSpeed) {
  43089. var runtimeAnimations = this._runtimeAnimations;
  43090. for (var index = 0; index < runtimeAnimations.length; index++) {
  43091. runtimeAnimations[index].animation.enableBlending = true;
  43092. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  43093. }
  43094. };
  43095. Animatable.prototype.disableBlending = function () {
  43096. var runtimeAnimations = this._runtimeAnimations;
  43097. for (var index = 0; index < runtimeAnimations.length; index++) {
  43098. runtimeAnimations[index].animation.enableBlending = false;
  43099. }
  43100. };
  43101. Animatable.prototype.goToFrame = function (frame) {
  43102. var runtimeAnimations = this._runtimeAnimations;
  43103. if (runtimeAnimations[0]) {
  43104. var fps = runtimeAnimations[0].animation.framePerSecond;
  43105. var currentFrame = runtimeAnimations[0].currentFrame;
  43106. var adjustTime = frame - currentFrame;
  43107. var delay = adjustTime * 1000 / fps;
  43108. if (this._localDelayOffset === null) {
  43109. this._localDelayOffset = 0;
  43110. }
  43111. this._localDelayOffset -= delay;
  43112. }
  43113. for (var index = 0; index < runtimeAnimations.length; index++) {
  43114. runtimeAnimations[index].goToFrame(frame);
  43115. }
  43116. };
  43117. Animatable.prototype.pause = function () {
  43118. if (this._paused) {
  43119. return;
  43120. }
  43121. this._paused = true;
  43122. };
  43123. Animatable.prototype.restart = function () {
  43124. this._paused = false;
  43125. };
  43126. Animatable.prototype.stop = function (animationName) {
  43127. if (animationName) {
  43128. var idx = this._scene._activeAnimatables.indexOf(this);
  43129. if (idx > -1) {
  43130. var runtimeAnimations = this._runtimeAnimations;
  43131. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  43132. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  43133. continue;
  43134. }
  43135. runtimeAnimations[index].dispose();
  43136. runtimeAnimations.splice(index, 1);
  43137. }
  43138. if (runtimeAnimations.length == 0) {
  43139. this._scene._activeAnimatables.splice(idx, 1);
  43140. if (this.onAnimationEnd) {
  43141. this.onAnimationEnd();
  43142. }
  43143. }
  43144. }
  43145. }
  43146. else {
  43147. var index = this._scene._activeAnimatables.indexOf(this);
  43148. if (index > -1) {
  43149. this._scene._activeAnimatables.splice(index, 1);
  43150. var runtimeAnimations = this._runtimeAnimations;
  43151. for (var index = 0; index < runtimeAnimations.length; index++) {
  43152. runtimeAnimations[index].dispose();
  43153. }
  43154. if (this.onAnimationEnd) {
  43155. this.onAnimationEnd();
  43156. }
  43157. }
  43158. }
  43159. };
  43160. Animatable.prototype._animate = function (delay) {
  43161. if (this._paused) {
  43162. this.animationStarted = false;
  43163. if (this._pausedDelay === null) {
  43164. this._pausedDelay = delay;
  43165. }
  43166. return true;
  43167. }
  43168. if (this._localDelayOffset === null) {
  43169. this._localDelayOffset = delay;
  43170. }
  43171. else if (this._pausedDelay !== null) {
  43172. this._localDelayOffset += delay - this._pausedDelay;
  43173. this._pausedDelay = null;
  43174. }
  43175. // Animating
  43176. var running = false;
  43177. var runtimeAnimations = this._runtimeAnimations;
  43178. var index;
  43179. for (index = 0; index < runtimeAnimations.length; index++) {
  43180. var animation = runtimeAnimations[index];
  43181. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  43182. running = running || isRunning;
  43183. }
  43184. this.animationStarted = running;
  43185. if (!running) {
  43186. // Remove from active animatables
  43187. index = this._scene._activeAnimatables.indexOf(this);
  43188. this._scene._activeAnimatables.splice(index, 1);
  43189. // Dispose all runtime animations
  43190. for (index = 0; index < runtimeAnimations.length; index++) {
  43191. runtimeAnimations[index].dispose();
  43192. }
  43193. }
  43194. if (!running && this.onAnimationEnd) {
  43195. this.onAnimationEnd();
  43196. this.onAnimationEnd = null;
  43197. }
  43198. return running;
  43199. };
  43200. return Animatable;
  43201. }());
  43202. BABYLON.Animatable = Animatable;
  43203. })(BABYLON || (BABYLON = {}));
  43204. //# sourceMappingURL=babylon.animatable.js.map
  43205. var BABYLON;
  43206. (function (BABYLON) {
  43207. var EasingFunction = /** @class */ (function () {
  43208. function EasingFunction() {
  43209. // Properties
  43210. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  43211. }
  43212. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  43213. get: function () {
  43214. return EasingFunction._EASINGMODE_EASEIN;
  43215. },
  43216. enumerable: true,
  43217. configurable: true
  43218. });
  43219. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  43220. get: function () {
  43221. return EasingFunction._EASINGMODE_EASEOUT;
  43222. },
  43223. enumerable: true,
  43224. configurable: true
  43225. });
  43226. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  43227. get: function () {
  43228. return EasingFunction._EASINGMODE_EASEINOUT;
  43229. },
  43230. enumerable: true,
  43231. configurable: true
  43232. });
  43233. EasingFunction.prototype.setEasingMode = function (easingMode) {
  43234. var n = Math.min(Math.max(easingMode, 0), 2);
  43235. this._easingMode = n;
  43236. };
  43237. EasingFunction.prototype.getEasingMode = function () {
  43238. return this._easingMode;
  43239. };
  43240. EasingFunction.prototype.easeInCore = function (gradient) {
  43241. throw new Error('You must implement this method');
  43242. };
  43243. EasingFunction.prototype.ease = function (gradient) {
  43244. switch (this._easingMode) {
  43245. case EasingFunction.EASINGMODE_EASEIN:
  43246. return this.easeInCore(gradient);
  43247. case EasingFunction.EASINGMODE_EASEOUT:
  43248. return (1 - this.easeInCore(1 - gradient));
  43249. }
  43250. if (gradient >= 0.5) {
  43251. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  43252. }
  43253. return (this.easeInCore(gradient * 2) * 0.5);
  43254. };
  43255. //Statics
  43256. EasingFunction._EASINGMODE_EASEIN = 0;
  43257. EasingFunction._EASINGMODE_EASEOUT = 1;
  43258. EasingFunction._EASINGMODE_EASEINOUT = 2;
  43259. return EasingFunction;
  43260. }());
  43261. BABYLON.EasingFunction = EasingFunction;
  43262. var CircleEase = /** @class */ (function (_super) {
  43263. __extends(CircleEase, _super);
  43264. function CircleEase() {
  43265. return _super !== null && _super.apply(this, arguments) || this;
  43266. }
  43267. CircleEase.prototype.easeInCore = function (gradient) {
  43268. gradient = Math.max(0, Math.min(1, gradient));
  43269. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  43270. };
  43271. return CircleEase;
  43272. }(EasingFunction));
  43273. BABYLON.CircleEase = CircleEase;
  43274. var BackEase = /** @class */ (function (_super) {
  43275. __extends(BackEase, _super);
  43276. function BackEase(amplitude) {
  43277. if (amplitude === void 0) { amplitude = 1; }
  43278. var _this = _super.call(this) || this;
  43279. _this.amplitude = amplitude;
  43280. return _this;
  43281. }
  43282. BackEase.prototype.easeInCore = function (gradient) {
  43283. var num = Math.max(0, this.amplitude);
  43284. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  43285. };
  43286. return BackEase;
  43287. }(EasingFunction));
  43288. BABYLON.BackEase = BackEase;
  43289. var BounceEase = /** @class */ (function (_super) {
  43290. __extends(BounceEase, _super);
  43291. function BounceEase(bounces, bounciness) {
  43292. if (bounces === void 0) { bounces = 3; }
  43293. if (bounciness === void 0) { bounciness = 2; }
  43294. var _this = _super.call(this) || this;
  43295. _this.bounces = bounces;
  43296. _this.bounciness = bounciness;
  43297. return _this;
  43298. }
  43299. BounceEase.prototype.easeInCore = function (gradient) {
  43300. var y = Math.max(0.0, this.bounces);
  43301. var bounciness = this.bounciness;
  43302. if (bounciness <= 1.0) {
  43303. bounciness = 1.001;
  43304. }
  43305. var num9 = Math.pow(bounciness, y);
  43306. var num5 = 1.0 - bounciness;
  43307. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  43308. var num15 = gradient * num4;
  43309. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  43310. var num3 = Math.floor(num65);
  43311. var num13 = num3 + 1.0;
  43312. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  43313. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  43314. var num7 = (num8 + num12) * 0.5;
  43315. var num6 = gradient - num7;
  43316. var num2 = num7 - num8;
  43317. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  43318. };
  43319. return BounceEase;
  43320. }(EasingFunction));
  43321. BABYLON.BounceEase = BounceEase;
  43322. var CubicEase = /** @class */ (function (_super) {
  43323. __extends(CubicEase, _super);
  43324. function CubicEase() {
  43325. return _super !== null && _super.apply(this, arguments) || this;
  43326. }
  43327. CubicEase.prototype.easeInCore = function (gradient) {
  43328. return (gradient * gradient * gradient);
  43329. };
  43330. return CubicEase;
  43331. }(EasingFunction));
  43332. BABYLON.CubicEase = CubicEase;
  43333. var ElasticEase = /** @class */ (function (_super) {
  43334. __extends(ElasticEase, _super);
  43335. function ElasticEase(oscillations, springiness) {
  43336. if (oscillations === void 0) { oscillations = 3; }
  43337. if (springiness === void 0) { springiness = 3; }
  43338. var _this = _super.call(this) || this;
  43339. _this.oscillations = oscillations;
  43340. _this.springiness = springiness;
  43341. return _this;
  43342. }
  43343. ElasticEase.prototype.easeInCore = function (gradient) {
  43344. var num2;
  43345. var num3 = Math.max(0.0, this.oscillations);
  43346. var num = Math.max(0.0, this.springiness);
  43347. if (num == 0) {
  43348. num2 = gradient;
  43349. }
  43350. else {
  43351. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  43352. }
  43353. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  43354. };
  43355. return ElasticEase;
  43356. }(EasingFunction));
  43357. BABYLON.ElasticEase = ElasticEase;
  43358. var ExponentialEase = /** @class */ (function (_super) {
  43359. __extends(ExponentialEase, _super);
  43360. function ExponentialEase(exponent) {
  43361. if (exponent === void 0) { exponent = 2; }
  43362. var _this = _super.call(this) || this;
  43363. _this.exponent = exponent;
  43364. return _this;
  43365. }
  43366. ExponentialEase.prototype.easeInCore = function (gradient) {
  43367. if (this.exponent <= 0) {
  43368. return gradient;
  43369. }
  43370. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  43371. };
  43372. return ExponentialEase;
  43373. }(EasingFunction));
  43374. BABYLON.ExponentialEase = ExponentialEase;
  43375. var PowerEase = /** @class */ (function (_super) {
  43376. __extends(PowerEase, _super);
  43377. function PowerEase(power) {
  43378. if (power === void 0) { power = 2; }
  43379. var _this = _super.call(this) || this;
  43380. _this.power = power;
  43381. return _this;
  43382. }
  43383. PowerEase.prototype.easeInCore = function (gradient) {
  43384. var y = Math.max(0.0, this.power);
  43385. return Math.pow(gradient, y);
  43386. };
  43387. return PowerEase;
  43388. }(EasingFunction));
  43389. BABYLON.PowerEase = PowerEase;
  43390. var QuadraticEase = /** @class */ (function (_super) {
  43391. __extends(QuadraticEase, _super);
  43392. function QuadraticEase() {
  43393. return _super !== null && _super.apply(this, arguments) || this;
  43394. }
  43395. QuadraticEase.prototype.easeInCore = function (gradient) {
  43396. return (gradient * gradient);
  43397. };
  43398. return QuadraticEase;
  43399. }(EasingFunction));
  43400. BABYLON.QuadraticEase = QuadraticEase;
  43401. var QuarticEase = /** @class */ (function (_super) {
  43402. __extends(QuarticEase, _super);
  43403. function QuarticEase() {
  43404. return _super !== null && _super.apply(this, arguments) || this;
  43405. }
  43406. QuarticEase.prototype.easeInCore = function (gradient) {
  43407. return (gradient * gradient * gradient * gradient);
  43408. };
  43409. return QuarticEase;
  43410. }(EasingFunction));
  43411. BABYLON.QuarticEase = QuarticEase;
  43412. var QuinticEase = /** @class */ (function (_super) {
  43413. __extends(QuinticEase, _super);
  43414. function QuinticEase() {
  43415. return _super !== null && _super.apply(this, arguments) || this;
  43416. }
  43417. QuinticEase.prototype.easeInCore = function (gradient) {
  43418. return (gradient * gradient * gradient * gradient * gradient);
  43419. };
  43420. return QuinticEase;
  43421. }(EasingFunction));
  43422. BABYLON.QuinticEase = QuinticEase;
  43423. var SineEase = /** @class */ (function (_super) {
  43424. __extends(SineEase, _super);
  43425. function SineEase() {
  43426. return _super !== null && _super.apply(this, arguments) || this;
  43427. }
  43428. SineEase.prototype.easeInCore = function (gradient) {
  43429. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  43430. };
  43431. return SineEase;
  43432. }(EasingFunction));
  43433. BABYLON.SineEase = SineEase;
  43434. var BezierCurveEase = /** @class */ (function (_super) {
  43435. __extends(BezierCurveEase, _super);
  43436. function BezierCurveEase(x1, y1, x2, y2) {
  43437. if (x1 === void 0) { x1 = 0; }
  43438. if (y1 === void 0) { y1 = 0; }
  43439. if (x2 === void 0) { x2 = 1; }
  43440. if (y2 === void 0) { y2 = 1; }
  43441. var _this = _super.call(this) || this;
  43442. _this.x1 = x1;
  43443. _this.y1 = y1;
  43444. _this.x2 = x2;
  43445. _this.y2 = y2;
  43446. return _this;
  43447. }
  43448. BezierCurveEase.prototype.easeInCore = function (gradient) {
  43449. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  43450. };
  43451. return BezierCurveEase;
  43452. }(EasingFunction));
  43453. BABYLON.BezierCurveEase = BezierCurveEase;
  43454. })(BABYLON || (BABYLON = {}));
  43455. //# sourceMappingURL=babylon.easing.js.map
  43456. var BABYLON;
  43457. (function (BABYLON) {
  43458. var Condition = /** @class */ (function () {
  43459. function Condition(actionManager) {
  43460. this._actionManager = actionManager;
  43461. }
  43462. Condition.prototype.isValid = function () {
  43463. return true;
  43464. };
  43465. Condition.prototype._getProperty = function (propertyPath) {
  43466. return this._actionManager._getProperty(propertyPath);
  43467. };
  43468. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  43469. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43470. };
  43471. Condition.prototype.serialize = function () {
  43472. };
  43473. Condition.prototype._serialize = function (serializedCondition) {
  43474. return {
  43475. type: 2,
  43476. children: [],
  43477. name: serializedCondition.name,
  43478. properties: serializedCondition.properties
  43479. };
  43480. };
  43481. return Condition;
  43482. }());
  43483. BABYLON.Condition = Condition;
  43484. var ValueCondition = /** @class */ (function (_super) {
  43485. __extends(ValueCondition, _super);
  43486. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  43487. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  43488. var _this = _super.call(this, actionManager) || this;
  43489. _this.propertyPath = propertyPath;
  43490. _this.value = value;
  43491. _this.operator = operator;
  43492. _this._target = target;
  43493. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  43494. _this._property = _this._getProperty(_this.propertyPath);
  43495. return _this;
  43496. }
  43497. Object.defineProperty(ValueCondition, "IsEqual", {
  43498. get: function () {
  43499. return ValueCondition._IsEqual;
  43500. },
  43501. enumerable: true,
  43502. configurable: true
  43503. });
  43504. Object.defineProperty(ValueCondition, "IsDifferent", {
  43505. get: function () {
  43506. return ValueCondition._IsDifferent;
  43507. },
  43508. enumerable: true,
  43509. configurable: true
  43510. });
  43511. Object.defineProperty(ValueCondition, "IsGreater", {
  43512. get: function () {
  43513. return ValueCondition._IsGreater;
  43514. },
  43515. enumerable: true,
  43516. configurable: true
  43517. });
  43518. Object.defineProperty(ValueCondition, "IsLesser", {
  43519. get: function () {
  43520. return ValueCondition._IsLesser;
  43521. },
  43522. enumerable: true,
  43523. configurable: true
  43524. });
  43525. // Methods
  43526. ValueCondition.prototype.isValid = function () {
  43527. switch (this.operator) {
  43528. case ValueCondition.IsGreater:
  43529. return this._effectiveTarget[this._property] > this.value;
  43530. case ValueCondition.IsLesser:
  43531. return this._effectiveTarget[this._property] < this.value;
  43532. case ValueCondition.IsEqual:
  43533. case ValueCondition.IsDifferent:
  43534. var check;
  43535. if (this.value.equals) {
  43536. check = this.value.equals(this._effectiveTarget[this._property]);
  43537. }
  43538. else {
  43539. check = this.value === this._effectiveTarget[this._property];
  43540. }
  43541. return this.operator === ValueCondition.IsEqual ? check : !check;
  43542. }
  43543. return false;
  43544. };
  43545. ValueCondition.prototype.serialize = function () {
  43546. return this._serialize({
  43547. name: "ValueCondition",
  43548. properties: [
  43549. BABYLON.Action._GetTargetProperty(this._target),
  43550. { name: "propertyPath", value: this.propertyPath },
  43551. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43552. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  43553. ]
  43554. });
  43555. };
  43556. ValueCondition.GetOperatorName = function (operator) {
  43557. switch (operator) {
  43558. case ValueCondition._IsEqual: return "IsEqual";
  43559. case ValueCondition._IsDifferent: return "IsDifferent";
  43560. case ValueCondition._IsGreater: return "IsGreater";
  43561. case ValueCondition._IsLesser: return "IsLesser";
  43562. default: return "";
  43563. }
  43564. };
  43565. // Statics
  43566. ValueCondition._IsEqual = 0;
  43567. ValueCondition._IsDifferent = 1;
  43568. ValueCondition._IsGreater = 2;
  43569. ValueCondition._IsLesser = 3;
  43570. return ValueCondition;
  43571. }(Condition));
  43572. BABYLON.ValueCondition = ValueCondition;
  43573. var PredicateCondition = /** @class */ (function (_super) {
  43574. __extends(PredicateCondition, _super);
  43575. function PredicateCondition(actionManager, predicate) {
  43576. var _this = _super.call(this, actionManager) || this;
  43577. _this.predicate = predicate;
  43578. return _this;
  43579. }
  43580. PredicateCondition.prototype.isValid = function () {
  43581. return this.predicate();
  43582. };
  43583. return PredicateCondition;
  43584. }(Condition));
  43585. BABYLON.PredicateCondition = PredicateCondition;
  43586. var StateCondition = /** @class */ (function (_super) {
  43587. __extends(StateCondition, _super);
  43588. function StateCondition(actionManager, target, value) {
  43589. var _this = _super.call(this, actionManager) || this;
  43590. _this.value = value;
  43591. _this._target = target;
  43592. return _this;
  43593. }
  43594. // Methods
  43595. StateCondition.prototype.isValid = function () {
  43596. return this._target.state === this.value;
  43597. };
  43598. StateCondition.prototype.serialize = function () {
  43599. return this._serialize({
  43600. name: "StateCondition",
  43601. properties: [
  43602. BABYLON.Action._GetTargetProperty(this._target),
  43603. { name: "value", value: this.value }
  43604. ]
  43605. });
  43606. };
  43607. return StateCondition;
  43608. }(Condition));
  43609. BABYLON.StateCondition = StateCondition;
  43610. })(BABYLON || (BABYLON = {}));
  43611. //# sourceMappingURL=babylon.condition.js.map
  43612. var BABYLON;
  43613. (function (BABYLON) {
  43614. var Action = /** @class */ (function () {
  43615. function Action(triggerOptions, condition) {
  43616. this.triggerOptions = triggerOptions;
  43617. this.onBeforeExecuteObservable = new BABYLON.Observable();
  43618. if (triggerOptions.parameter) {
  43619. this.trigger = triggerOptions.trigger;
  43620. this._triggerParameter = triggerOptions.parameter;
  43621. }
  43622. else {
  43623. this.trigger = triggerOptions;
  43624. }
  43625. this._nextActiveAction = this;
  43626. this._condition = condition;
  43627. }
  43628. // Methods
  43629. Action.prototype._prepare = function () {
  43630. };
  43631. Action.prototype.getTriggerParameter = function () {
  43632. return this._triggerParameter;
  43633. };
  43634. Action.prototype._executeCurrent = function (evt) {
  43635. if (this._nextActiveAction._condition) {
  43636. var condition = this._nextActiveAction._condition;
  43637. var currentRenderId = this._actionManager.getScene().getRenderId();
  43638. // We cache the current evaluation for the current frame
  43639. if (condition._evaluationId === currentRenderId) {
  43640. if (!condition._currentResult) {
  43641. return;
  43642. }
  43643. }
  43644. else {
  43645. condition._evaluationId = currentRenderId;
  43646. if (!condition.isValid()) {
  43647. condition._currentResult = false;
  43648. return;
  43649. }
  43650. condition._currentResult = true;
  43651. }
  43652. }
  43653. this.onBeforeExecuteObservable.notifyObservers(this);
  43654. this._nextActiveAction.execute(evt);
  43655. this.skipToNextActiveAction();
  43656. };
  43657. Action.prototype.execute = function (evt) {
  43658. };
  43659. Action.prototype.skipToNextActiveAction = function () {
  43660. if (this._nextActiveAction._child) {
  43661. if (!this._nextActiveAction._child._actionManager) {
  43662. this._nextActiveAction._child._actionManager = this._actionManager;
  43663. }
  43664. this._nextActiveAction = this._nextActiveAction._child;
  43665. }
  43666. else {
  43667. this._nextActiveAction = this;
  43668. }
  43669. };
  43670. Action.prototype.then = function (action) {
  43671. this._child = action;
  43672. action._actionManager = this._actionManager;
  43673. action._prepare();
  43674. return action;
  43675. };
  43676. Action.prototype._getProperty = function (propertyPath) {
  43677. return this._actionManager._getProperty(propertyPath);
  43678. };
  43679. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  43680. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43681. };
  43682. Action.prototype.serialize = function (parent) {
  43683. };
  43684. // Called by BABYLON.Action objects in serialize(...). Internal use
  43685. Action.prototype._serialize = function (serializedAction, parent) {
  43686. var serializationObject = {
  43687. type: 1,
  43688. children: [],
  43689. name: serializedAction.name,
  43690. properties: serializedAction.properties || []
  43691. };
  43692. // Serialize child
  43693. if (this._child) {
  43694. this._child.serialize(serializationObject);
  43695. }
  43696. // Check if "this" has a condition
  43697. if (this._condition) {
  43698. var serializedCondition = this._condition.serialize();
  43699. serializedCondition.children.push(serializationObject);
  43700. if (parent) {
  43701. parent.children.push(serializedCondition);
  43702. }
  43703. return serializedCondition;
  43704. }
  43705. if (parent) {
  43706. parent.children.push(serializationObject);
  43707. }
  43708. return serializationObject;
  43709. };
  43710. Action._SerializeValueAsString = function (value) {
  43711. if (typeof value === "number") {
  43712. return value.toString();
  43713. }
  43714. if (typeof value === "boolean") {
  43715. return value ? "true" : "false";
  43716. }
  43717. if (value instanceof BABYLON.Vector2) {
  43718. return value.x + ", " + value.y;
  43719. }
  43720. if (value instanceof BABYLON.Vector3) {
  43721. return value.x + ", " + value.y + ", " + value.z;
  43722. }
  43723. if (value instanceof BABYLON.Color3) {
  43724. return value.r + ", " + value.g + ", " + value.b;
  43725. }
  43726. if (value instanceof BABYLON.Color4) {
  43727. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  43728. }
  43729. return value; // string
  43730. };
  43731. Action._GetTargetProperty = function (target) {
  43732. return {
  43733. name: "target",
  43734. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  43735. : target instanceof BABYLON.Light ? "LightProperties"
  43736. : target instanceof BABYLON.Camera ? "CameraProperties"
  43737. : "SceneProperties",
  43738. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  43739. };
  43740. };
  43741. return Action;
  43742. }());
  43743. BABYLON.Action = Action;
  43744. })(BABYLON || (BABYLON = {}));
  43745. //# sourceMappingURL=babylon.action.js.map
  43746. var BABYLON;
  43747. (function (BABYLON) {
  43748. /**
  43749. * ActionEvent is the event beint sent when an action is triggered.
  43750. */
  43751. var ActionEvent = /** @class */ (function () {
  43752. /**
  43753. * @param source The mesh or sprite that triggered the action.
  43754. * @param pointerX The X mouse cursor position at the time of the event
  43755. * @param pointerY The Y mouse cursor position at the time of the event
  43756. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  43757. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  43758. */
  43759. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  43760. this.source = source;
  43761. this.pointerX = pointerX;
  43762. this.pointerY = pointerY;
  43763. this.meshUnderPointer = meshUnderPointer;
  43764. this.sourceEvent = sourceEvent;
  43765. this.additionalData = additionalData;
  43766. }
  43767. /**
  43768. * Helper function to auto-create an ActionEvent from a source mesh.
  43769. * @param source The source mesh that triggered the event
  43770. * @param evt {Event} The original (browser) event
  43771. */
  43772. ActionEvent.CreateNew = function (source, evt, additionalData) {
  43773. var scene = source.getScene();
  43774. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43775. };
  43776. /**
  43777. * Helper function to auto-create an ActionEvent from a source mesh.
  43778. * @param source The source sprite that triggered the event
  43779. * @param scene Scene associated with the sprite
  43780. * @param evt {Event} The original (browser) event
  43781. */
  43782. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  43783. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43784. };
  43785. /**
  43786. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  43787. * @param scene the scene where the event occurred
  43788. * @param evt {Event} The original (browser) event
  43789. */
  43790. ActionEvent.CreateNewFromScene = function (scene, evt) {
  43791. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  43792. };
  43793. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  43794. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  43795. };
  43796. return ActionEvent;
  43797. }());
  43798. BABYLON.ActionEvent = ActionEvent;
  43799. /**
  43800. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  43801. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  43802. */
  43803. var ActionManager = /** @class */ (function () {
  43804. function ActionManager(scene) {
  43805. // Members
  43806. this.actions = new Array();
  43807. this.hoverCursor = '';
  43808. this._scene = scene;
  43809. scene._actionManagers.push(this);
  43810. }
  43811. Object.defineProperty(ActionManager, "NothingTrigger", {
  43812. get: function () {
  43813. return ActionManager._NothingTrigger;
  43814. },
  43815. enumerable: true,
  43816. configurable: true
  43817. });
  43818. Object.defineProperty(ActionManager, "OnPickTrigger", {
  43819. get: function () {
  43820. return ActionManager._OnPickTrigger;
  43821. },
  43822. enumerable: true,
  43823. configurable: true
  43824. });
  43825. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  43826. get: function () {
  43827. return ActionManager._OnLeftPickTrigger;
  43828. },
  43829. enumerable: true,
  43830. configurable: true
  43831. });
  43832. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  43833. get: function () {
  43834. return ActionManager._OnRightPickTrigger;
  43835. },
  43836. enumerable: true,
  43837. configurable: true
  43838. });
  43839. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  43840. get: function () {
  43841. return ActionManager._OnCenterPickTrigger;
  43842. },
  43843. enumerable: true,
  43844. configurable: true
  43845. });
  43846. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  43847. get: function () {
  43848. return ActionManager._OnPickDownTrigger;
  43849. },
  43850. enumerable: true,
  43851. configurable: true
  43852. });
  43853. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  43854. get: function () {
  43855. return ActionManager._OnDoublePickTrigger;
  43856. },
  43857. enumerable: true,
  43858. configurable: true
  43859. });
  43860. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  43861. get: function () {
  43862. return ActionManager._OnPickUpTrigger;
  43863. },
  43864. enumerable: true,
  43865. configurable: true
  43866. });
  43867. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  43868. /// This trigger will only be raised if you also declared a OnPickDown
  43869. get: function () {
  43870. return ActionManager._OnPickOutTrigger;
  43871. },
  43872. enumerable: true,
  43873. configurable: true
  43874. });
  43875. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  43876. get: function () {
  43877. return ActionManager._OnLongPressTrigger;
  43878. },
  43879. enumerable: true,
  43880. configurable: true
  43881. });
  43882. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  43883. get: function () {
  43884. return ActionManager._OnPointerOverTrigger;
  43885. },
  43886. enumerable: true,
  43887. configurable: true
  43888. });
  43889. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  43890. get: function () {
  43891. return ActionManager._OnPointerOutTrigger;
  43892. },
  43893. enumerable: true,
  43894. configurable: true
  43895. });
  43896. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  43897. get: function () {
  43898. return ActionManager._OnEveryFrameTrigger;
  43899. },
  43900. enumerable: true,
  43901. configurable: true
  43902. });
  43903. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  43904. get: function () {
  43905. return ActionManager._OnIntersectionEnterTrigger;
  43906. },
  43907. enumerable: true,
  43908. configurable: true
  43909. });
  43910. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  43911. get: function () {
  43912. return ActionManager._OnIntersectionExitTrigger;
  43913. },
  43914. enumerable: true,
  43915. configurable: true
  43916. });
  43917. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  43918. get: function () {
  43919. return ActionManager._OnKeyDownTrigger;
  43920. },
  43921. enumerable: true,
  43922. configurable: true
  43923. });
  43924. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  43925. get: function () {
  43926. return ActionManager._OnKeyUpTrigger;
  43927. },
  43928. enumerable: true,
  43929. configurable: true
  43930. });
  43931. // Methods
  43932. ActionManager.prototype.dispose = function () {
  43933. var index = this._scene._actionManagers.indexOf(this);
  43934. for (var i = 0; i < this.actions.length; i++) {
  43935. var action = this.actions[i];
  43936. ActionManager.Triggers[action.trigger]--;
  43937. if (ActionManager.Triggers[action.trigger] === 0) {
  43938. delete ActionManager.Triggers[action.trigger];
  43939. }
  43940. }
  43941. if (index > -1) {
  43942. this._scene._actionManagers.splice(index, 1);
  43943. }
  43944. };
  43945. ActionManager.prototype.getScene = function () {
  43946. return this._scene;
  43947. };
  43948. /**
  43949. * Does this action manager handles actions of any of the given triggers
  43950. * @param {number[]} triggers - the triggers to be tested
  43951. * @return {boolean} whether one (or more) of the triggers is handeled
  43952. */
  43953. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  43954. for (var index = 0; index < this.actions.length; index++) {
  43955. var action = this.actions[index];
  43956. if (triggers.indexOf(action.trigger) > -1) {
  43957. return true;
  43958. }
  43959. }
  43960. return false;
  43961. };
  43962. /**
  43963. * Does this action manager handles actions of a given trigger
  43964. * @param {number} trigger - the trigger to be tested
  43965. * @return {boolean} whether the trigger is handeled
  43966. */
  43967. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  43968. for (var index = 0; index < this.actions.length; index++) {
  43969. var action = this.actions[index];
  43970. if (action.trigger === trigger) {
  43971. return true;
  43972. }
  43973. }
  43974. return false;
  43975. };
  43976. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  43977. /**
  43978. * Does this action manager has pointer triggers
  43979. * @return {boolean} whether or not it has pointer triggers
  43980. */
  43981. get: function () {
  43982. for (var index = 0; index < this.actions.length; index++) {
  43983. var action = this.actions[index];
  43984. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  43985. return true;
  43986. }
  43987. }
  43988. return false;
  43989. },
  43990. enumerable: true,
  43991. configurable: true
  43992. });
  43993. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  43994. /**
  43995. * Does this action manager has pick triggers
  43996. * @return {boolean} whether or not it has pick triggers
  43997. */
  43998. get: function () {
  43999. for (var index = 0; index < this.actions.length; index++) {
  44000. var action = this.actions[index];
  44001. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  44002. return true;
  44003. }
  44004. }
  44005. return false;
  44006. },
  44007. enumerable: true,
  44008. configurable: true
  44009. });
  44010. Object.defineProperty(ActionManager, "HasTriggers", {
  44011. /**
  44012. * Does exist one action manager with at least one trigger
  44013. * @return {boolean} whether or not it exists one action manager with one trigger
  44014. **/
  44015. get: function () {
  44016. for (var t in ActionManager.Triggers) {
  44017. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44018. return true;
  44019. }
  44020. }
  44021. return false;
  44022. },
  44023. enumerable: true,
  44024. configurable: true
  44025. });
  44026. Object.defineProperty(ActionManager, "HasPickTriggers", {
  44027. /**
  44028. * Does exist one action manager with at least one pick trigger
  44029. * @return {boolean} whether or not it exists one action manager with one pick trigger
  44030. **/
  44031. get: function () {
  44032. for (var t in ActionManager.Triggers) {
  44033. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44034. var t_int = parseInt(t);
  44035. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  44036. return true;
  44037. }
  44038. }
  44039. }
  44040. return false;
  44041. },
  44042. enumerable: true,
  44043. configurable: true
  44044. });
  44045. /**
  44046. * Does exist one action manager that handles actions of a given trigger
  44047. * @param {number} trigger - the trigger to be tested
  44048. * @return {boolean} whether the trigger is handeled by at least one action manager
  44049. **/
  44050. ActionManager.HasSpecificTrigger = function (trigger) {
  44051. for (var t in ActionManager.Triggers) {
  44052. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44053. var t_int = parseInt(t);
  44054. if (t_int === trigger) {
  44055. return true;
  44056. }
  44057. }
  44058. }
  44059. return false;
  44060. };
  44061. /**
  44062. * Registers an action to this action manager
  44063. * @param {BABYLON.Action} action - the action to be registered
  44064. * @return {BABYLON.Action} the action amended (prepared) after registration
  44065. */
  44066. ActionManager.prototype.registerAction = function (action) {
  44067. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  44068. if (this.getScene().actionManager !== this) {
  44069. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  44070. return null;
  44071. }
  44072. }
  44073. this.actions.push(action);
  44074. if (ActionManager.Triggers[action.trigger]) {
  44075. ActionManager.Triggers[action.trigger]++;
  44076. }
  44077. else {
  44078. ActionManager.Triggers[action.trigger] = 1;
  44079. }
  44080. action._actionManager = this;
  44081. action._prepare();
  44082. return action;
  44083. };
  44084. /**
  44085. * Process a specific trigger
  44086. * @param {number} trigger - the trigger to process
  44087. * @param evt {BABYLON.ActionEvent} the event details to be processed
  44088. */
  44089. ActionManager.prototype.processTrigger = function (trigger, evt) {
  44090. for (var index = 0; index < this.actions.length; index++) {
  44091. var action = this.actions[index];
  44092. if (action.trigger === trigger) {
  44093. if (evt) {
  44094. if (trigger === ActionManager.OnKeyUpTrigger
  44095. || trigger === ActionManager.OnKeyDownTrigger) {
  44096. var parameter = action.getTriggerParameter();
  44097. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  44098. if (!parameter.toLowerCase) {
  44099. continue;
  44100. }
  44101. var lowerCase = parameter.toLowerCase();
  44102. if (lowerCase !== evt.sourceEvent.key) {
  44103. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  44104. var actualkey = String.fromCharCode(unicode).toLowerCase();
  44105. if (actualkey !== lowerCase) {
  44106. continue;
  44107. }
  44108. }
  44109. }
  44110. }
  44111. }
  44112. action._executeCurrent(evt);
  44113. }
  44114. }
  44115. };
  44116. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  44117. var properties = propertyPath.split(".");
  44118. for (var index = 0; index < properties.length - 1; index++) {
  44119. target = target[properties[index]];
  44120. }
  44121. return target;
  44122. };
  44123. ActionManager.prototype._getProperty = function (propertyPath) {
  44124. var properties = propertyPath.split(".");
  44125. return properties[properties.length - 1];
  44126. };
  44127. ActionManager.prototype.serialize = function (name) {
  44128. var root = {
  44129. children: new Array(),
  44130. name: name,
  44131. type: 3,
  44132. properties: new Array() // Empty for root but required
  44133. };
  44134. for (var i = 0; i < this.actions.length; i++) {
  44135. var triggerObject = {
  44136. type: 0,
  44137. children: new Array(),
  44138. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  44139. properties: new Array()
  44140. };
  44141. var triggerOptions = this.actions[i].triggerOptions;
  44142. if (triggerOptions && typeof triggerOptions !== "number") {
  44143. if (triggerOptions.parameter instanceof BABYLON.Node) {
  44144. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  44145. }
  44146. else {
  44147. var parameter = {};
  44148. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  44149. if (triggerOptions.parameter.mesh) {
  44150. parameter._meshId = triggerOptions.parameter.mesh.id;
  44151. }
  44152. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  44153. }
  44154. }
  44155. // Serialize child action, recursively
  44156. this.actions[i].serialize(triggerObject);
  44157. // Add serialized trigger
  44158. root.children.push(triggerObject);
  44159. }
  44160. return root;
  44161. };
  44162. ActionManager.Parse = function (parsedActions, object, scene) {
  44163. var actionManager = new ActionManager(scene);
  44164. if (object === null)
  44165. scene.actionManager = actionManager;
  44166. else
  44167. object.actionManager = actionManager;
  44168. // instanciate a new object
  44169. var instanciate = function (name, params) {
  44170. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  44171. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  44172. newInstance.constructor.apply(newInstance, params);
  44173. return newInstance;
  44174. };
  44175. var parseParameter = function (name, value, target, propertyPath) {
  44176. if (propertyPath === null) {
  44177. // String, boolean or float
  44178. var floatValue = parseFloat(value);
  44179. if (value === "true" || value === "false")
  44180. return value === "true";
  44181. else
  44182. return isNaN(floatValue) ? value : floatValue;
  44183. }
  44184. var effectiveTarget = propertyPath.split(".");
  44185. var values = value.split(",");
  44186. // Get effective Target
  44187. for (var i = 0; i < effectiveTarget.length; i++) {
  44188. target = target[effectiveTarget[i]];
  44189. }
  44190. // Return appropriate value with its type
  44191. if (typeof (target) === "boolean")
  44192. return values[0] === "true";
  44193. if (typeof (target) === "string")
  44194. return values[0];
  44195. // Parameters with multiple values such as Vector3 etc.
  44196. var split = new Array();
  44197. for (var i = 0; i < values.length; i++)
  44198. split.push(parseFloat(values[i]));
  44199. if (target instanceof BABYLON.Vector3)
  44200. return BABYLON.Vector3.FromArray(split);
  44201. if (target instanceof BABYLON.Vector4)
  44202. return BABYLON.Vector4.FromArray(split);
  44203. if (target instanceof BABYLON.Color3)
  44204. return BABYLON.Color3.FromArray(split);
  44205. if (target instanceof BABYLON.Color4)
  44206. return BABYLON.Color4.FromArray(split);
  44207. return parseFloat(values[0]);
  44208. };
  44209. // traverse graph per trigger
  44210. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  44211. if (combineArray === void 0) { combineArray = null; }
  44212. if (parsedAction.detached)
  44213. return;
  44214. var parameters = new Array();
  44215. var target = null;
  44216. var propertyPath = null;
  44217. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  44218. // Parameters
  44219. if (parsedAction.type === 2)
  44220. parameters.push(actionManager);
  44221. else
  44222. parameters.push(trigger);
  44223. if (combine) {
  44224. var actions = new Array();
  44225. for (var j = 0; j < parsedAction.combine.length; j++) {
  44226. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  44227. }
  44228. parameters.push(actions);
  44229. }
  44230. else {
  44231. for (var i = 0; i < parsedAction.properties.length; i++) {
  44232. var value = parsedAction.properties[i].value;
  44233. var name = parsedAction.properties[i].name;
  44234. var targetType = parsedAction.properties[i].targetType;
  44235. if (name === "target")
  44236. if (targetType !== null && targetType === "SceneProperties")
  44237. value = target = scene;
  44238. else
  44239. value = target = scene.getNodeByName(value);
  44240. else if (name === "parent")
  44241. value = scene.getNodeByName(value);
  44242. else if (name === "sound")
  44243. value = scene.getSoundByName(value);
  44244. else if (name !== "propertyPath") {
  44245. if (parsedAction.type === 2 && name === "operator")
  44246. value = BABYLON.ValueCondition[value];
  44247. else
  44248. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  44249. }
  44250. else {
  44251. propertyPath = value;
  44252. }
  44253. parameters.push(value);
  44254. }
  44255. }
  44256. if (combineArray === null) {
  44257. parameters.push(condition);
  44258. }
  44259. else {
  44260. parameters.push(null);
  44261. }
  44262. // If interpolate value action
  44263. if (parsedAction.name === "InterpolateValueAction") {
  44264. var param = parameters[parameters.length - 2];
  44265. parameters[parameters.length - 1] = param;
  44266. parameters[parameters.length - 2] = condition;
  44267. }
  44268. // Action or condition(s) and not CombineAction
  44269. var newAction = instanciate(parsedAction.name, parameters);
  44270. if (newAction instanceof BABYLON.Condition && condition !== null) {
  44271. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  44272. if (action)
  44273. action.then(nothing);
  44274. else
  44275. actionManager.registerAction(nothing);
  44276. action = nothing;
  44277. }
  44278. if (combineArray === null) {
  44279. if (newAction instanceof BABYLON.Condition) {
  44280. condition = newAction;
  44281. newAction = action;
  44282. }
  44283. else {
  44284. condition = null;
  44285. if (action)
  44286. action.then(newAction);
  44287. else
  44288. actionManager.registerAction(newAction);
  44289. }
  44290. }
  44291. else {
  44292. combineArray.push(newAction);
  44293. }
  44294. for (var i = 0; i < parsedAction.children.length; i++)
  44295. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  44296. };
  44297. // triggers
  44298. for (var i = 0; i < parsedActions.children.length; i++) {
  44299. var triggerParams;
  44300. var trigger = parsedActions.children[i];
  44301. if (trigger.properties.length > 0) {
  44302. var param = trigger.properties[0].value;
  44303. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  44304. if (value._meshId) {
  44305. value.mesh = scene.getMeshByID(value._meshId);
  44306. }
  44307. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  44308. }
  44309. else
  44310. triggerParams = ActionManager[trigger.name];
  44311. for (var j = 0; j < trigger.children.length; j++) {
  44312. if (!trigger.detached)
  44313. traverse(trigger.children[j], triggerParams, null, null);
  44314. }
  44315. }
  44316. };
  44317. ActionManager.GetTriggerName = function (trigger) {
  44318. switch (trigger) {
  44319. case 0: return "NothingTrigger";
  44320. case 1: return "OnPickTrigger";
  44321. case 2: return "OnLeftPickTrigger";
  44322. case 3: return "OnRightPickTrigger";
  44323. case 4: return "OnCenterPickTrigger";
  44324. case 5: return "OnPickDownTrigger";
  44325. case 6: return "OnPickUpTrigger";
  44326. case 7: return "OnLongPressTrigger";
  44327. case 8: return "OnPointerOverTrigger";
  44328. case 9: return "OnPointerOutTrigger";
  44329. case 10: return "OnEveryFrameTrigger";
  44330. case 11: return "OnIntersectionEnterTrigger";
  44331. case 12: return "OnIntersectionExitTrigger";
  44332. case 13: return "OnKeyDownTrigger";
  44333. case 14: return "OnKeyUpTrigger";
  44334. case 15: return "OnPickOutTrigger";
  44335. default: return "";
  44336. }
  44337. };
  44338. // Statics
  44339. ActionManager._NothingTrigger = 0;
  44340. ActionManager._OnPickTrigger = 1;
  44341. ActionManager._OnLeftPickTrigger = 2;
  44342. ActionManager._OnRightPickTrigger = 3;
  44343. ActionManager._OnCenterPickTrigger = 4;
  44344. ActionManager._OnPickDownTrigger = 5;
  44345. ActionManager._OnDoublePickTrigger = 6;
  44346. ActionManager._OnPickUpTrigger = 7;
  44347. ActionManager._OnLongPressTrigger = 8;
  44348. ActionManager._OnPointerOverTrigger = 9;
  44349. ActionManager._OnPointerOutTrigger = 10;
  44350. ActionManager._OnEveryFrameTrigger = 11;
  44351. ActionManager._OnIntersectionEnterTrigger = 12;
  44352. ActionManager._OnIntersectionExitTrigger = 13;
  44353. ActionManager._OnKeyDownTrigger = 14;
  44354. ActionManager._OnKeyUpTrigger = 15;
  44355. ActionManager._OnPickOutTrigger = 16;
  44356. ActionManager.Triggers = {};
  44357. return ActionManager;
  44358. }());
  44359. BABYLON.ActionManager = ActionManager;
  44360. })(BABYLON || (BABYLON = {}));
  44361. //# sourceMappingURL=babylon.actionManager.js.map
  44362. var BABYLON;
  44363. (function (BABYLON) {
  44364. var InterpolateValueAction = /** @class */ (function (_super) {
  44365. __extends(InterpolateValueAction, _super);
  44366. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  44367. if (duration === void 0) { duration = 1000; }
  44368. var _this = _super.call(this, triggerOptions, condition) || this;
  44369. _this.propertyPath = propertyPath;
  44370. _this.value = value;
  44371. _this.duration = duration;
  44372. _this.stopOtherAnimations = stopOtherAnimations;
  44373. _this.onInterpolationDone = onInterpolationDone;
  44374. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  44375. _this._target = _this._effectiveTarget = target;
  44376. return _this;
  44377. }
  44378. InterpolateValueAction.prototype._prepare = function () {
  44379. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44380. this._property = this._getProperty(this.propertyPath);
  44381. };
  44382. InterpolateValueAction.prototype.execute = function () {
  44383. var _this = this;
  44384. var scene = this._actionManager.getScene();
  44385. var keys = [
  44386. {
  44387. frame: 0,
  44388. value: this._effectiveTarget[this._property]
  44389. }, {
  44390. frame: 100,
  44391. value: this.value
  44392. }
  44393. ];
  44394. var dataType;
  44395. if (typeof this.value === "number") {
  44396. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  44397. }
  44398. else if (this.value instanceof BABYLON.Color3) {
  44399. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  44400. }
  44401. else if (this.value instanceof BABYLON.Vector3) {
  44402. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  44403. }
  44404. else if (this.value instanceof BABYLON.Matrix) {
  44405. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  44406. }
  44407. else if (this.value instanceof BABYLON.Quaternion) {
  44408. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  44409. }
  44410. else {
  44411. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  44412. return;
  44413. }
  44414. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  44415. animation.setKeys(keys);
  44416. if (this.stopOtherAnimations) {
  44417. scene.stopAnimation(this._effectiveTarget);
  44418. }
  44419. var wrapper = function () {
  44420. _this.onInterpolationDoneObservable.notifyObservers(_this);
  44421. if (_this.onInterpolationDone) {
  44422. _this.onInterpolationDone();
  44423. }
  44424. };
  44425. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  44426. };
  44427. InterpolateValueAction.prototype.serialize = function (parent) {
  44428. return _super.prototype._serialize.call(this, {
  44429. name: "InterpolateValueAction",
  44430. properties: [
  44431. BABYLON.Action._GetTargetProperty(this._target),
  44432. { name: "propertyPath", value: this.propertyPath },
  44433. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44434. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  44435. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  44436. ]
  44437. }, parent);
  44438. };
  44439. return InterpolateValueAction;
  44440. }(BABYLON.Action));
  44441. BABYLON.InterpolateValueAction = InterpolateValueAction;
  44442. })(BABYLON || (BABYLON = {}));
  44443. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  44444. var BABYLON;
  44445. (function (BABYLON) {
  44446. var SwitchBooleanAction = /** @class */ (function (_super) {
  44447. __extends(SwitchBooleanAction, _super);
  44448. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  44449. var _this = _super.call(this, triggerOptions, condition) || this;
  44450. _this.propertyPath = propertyPath;
  44451. _this._target = _this._effectiveTarget = target;
  44452. return _this;
  44453. }
  44454. SwitchBooleanAction.prototype._prepare = function () {
  44455. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44456. this._property = this._getProperty(this.propertyPath);
  44457. };
  44458. SwitchBooleanAction.prototype.execute = function () {
  44459. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  44460. };
  44461. SwitchBooleanAction.prototype.serialize = function (parent) {
  44462. return _super.prototype._serialize.call(this, {
  44463. name: "SwitchBooleanAction",
  44464. properties: [
  44465. BABYLON.Action._GetTargetProperty(this._target),
  44466. { name: "propertyPath", value: this.propertyPath }
  44467. ]
  44468. }, parent);
  44469. };
  44470. return SwitchBooleanAction;
  44471. }(BABYLON.Action));
  44472. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  44473. var SetStateAction = /** @class */ (function (_super) {
  44474. __extends(SetStateAction, _super);
  44475. function SetStateAction(triggerOptions, target, value, condition) {
  44476. var _this = _super.call(this, triggerOptions, condition) || this;
  44477. _this.value = value;
  44478. _this._target = target;
  44479. return _this;
  44480. }
  44481. SetStateAction.prototype.execute = function () {
  44482. this._target.state = this.value;
  44483. };
  44484. SetStateAction.prototype.serialize = function (parent) {
  44485. return _super.prototype._serialize.call(this, {
  44486. name: "SetStateAction",
  44487. properties: [
  44488. BABYLON.Action._GetTargetProperty(this._target),
  44489. { name: "value", value: this.value }
  44490. ]
  44491. }, parent);
  44492. };
  44493. return SetStateAction;
  44494. }(BABYLON.Action));
  44495. BABYLON.SetStateAction = SetStateAction;
  44496. var SetValueAction = /** @class */ (function (_super) {
  44497. __extends(SetValueAction, _super);
  44498. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  44499. var _this = _super.call(this, triggerOptions, condition) || this;
  44500. _this.propertyPath = propertyPath;
  44501. _this.value = value;
  44502. _this._target = _this._effectiveTarget = target;
  44503. return _this;
  44504. }
  44505. SetValueAction.prototype._prepare = function () {
  44506. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44507. this._property = this._getProperty(this.propertyPath);
  44508. };
  44509. SetValueAction.prototype.execute = function () {
  44510. this._effectiveTarget[this._property] = this.value;
  44511. if (this._target.markAsDirty) {
  44512. this._target.markAsDirty(this._property);
  44513. }
  44514. };
  44515. SetValueAction.prototype.serialize = function (parent) {
  44516. return _super.prototype._serialize.call(this, {
  44517. name: "SetValueAction",
  44518. properties: [
  44519. BABYLON.Action._GetTargetProperty(this._target),
  44520. { name: "propertyPath", value: this.propertyPath },
  44521. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44522. ]
  44523. }, parent);
  44524. };
  44525. return SetValueAction;
  44526. }(BABYLON.Action));
  44527. BABYLON.SetValueAction = SetValueAction;
  44528. var IncrementValueAction = /** @class */ (function (_super) {
  44529. __extends(IncrementValueAction, _super);
  44530. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  44531. var _this = _super.call(this, triggerOptions, condition) || this;
  44532. _this.propertyPath = propertyPath;
  44533. _this.value = value;
  44534. _this._target = _this._effectiveTarget = target;
  44535. return _this;
  44536. }
  44537. IncrementValueAction.prototype._prepare = function () {
  44538. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44539. this._property = this._getProperty(this.propertyPath);
  44540. if (typeof this._effectiveTarget[this._property] !== "number") {
  44541. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  44542. }
  44543. };
  44544. IncrementValueAction.prototype.execute = function () {
  44545. this._effectiveTarget[this._property] += this.value;
  44546. if (this._target.markAsDirty) {
  44547. this._target.markAsDirty(this._property);
  44548. }
  44549. };
  44550. IncrementValueAction.prototype.serialize = function (parent) {
  44551. return _super.prototype._serialize.call(this, {
  44552. name: "IncrementValueAction",
  44553. properties: [
  44554. BABYLON.Action._GetTargetProperty(this._target),
  44555. { name: "propertyPath", value: this.propertyPath },
  44556. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44557. ]
  44558. }, parent);
  44559. };
  44560. return IncrementValueAction;
  44561. }(BABYLON.Action));
  44562. BABYLON.IncrementValueAction = IncrementValueAction;
  44563. var PlayAnimationAction = /** @class */ (function (_super) {
  44564. __extends(PlayAnimationAction, _super);
  44565. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  44566. var _this = _super.call(this, triggerOptions, condition) || this;
  44567. _this.from = from;
  44568. _this.to = to;
  44569. _this.loop = loop;
  44570. _this._target = target;
  44571. return _this;
  44572. }
  44573. PlayAnimationAction.prototype._prepare = function () {
  44574. };
  44575. PlayAnimationAction.prototype.execute = function () {
  44576. var scene = this._actionManager.getScene();
  44577. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  44578. };
  44579. PlayAnimationAction.prototype.serialize = function (parent) {
  44580. return _super.prototype._serialize.call(this, {
  44581. name: "PlayAnimationAction",
  44582. properties: [
  44583. BABYLON.Action._GetTargetProperty(this._target),
  44584. { name: "from", value: String(this.from) },
  44585. { name: "to", value: String(this.to) },
  44586. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  44587. ]
  44588. }, parent);
  44589. };
  44590. return PlayAnimationAction;
  44591. }(BABYLON.Action));
  44592. BABYLON.PlayAnimationAction = PlayAnimationAction;
  44593. var StopAnimationAction = /** @class */ (function (_super) {
  44594. __extends(StopAnimationAction, _super);
  44595. function StopAnimationAction(triggerOptions, target, condition) {
  44596. var _this = _super.call(this, triggerOptions, condition) || this;
  44597. _this._target = target;
  44598. return _this;
  44599. }
  44600. StopAnimationAction.prototype._prepare = function () {
  44601. };
  44602. StopAnimationAction.prototype.execute = function () {
  44603. var scene = this._actionManager.getScene();
  44604. scene.stopAnimation(this._target);
  44605. };
  44606. StopAnimationAction.prototype.serialize = function (parent) {
  44607. return _super.prototype._serialize.call(this, {
  44608. name: "StopAnimationAction",
  44609. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  44610. }, parent);
  44611. };
  44612. return StopAnimationAction;
  44613. }(BABYLON.Action));
  44614. BABYLON.StopAnimationAction = StopAnimationAction;
  44615. var DoNothingAction = /** @class */ (function (_super) {
  44616. __extends(DoNothingAction, _super);
  44617. function DoNothingAction(triggerOptions, condition) {
  44618. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  44619. return _super.call(this, triggerOptions, condition) || this;
  44620. }
  44621. DoNothingAction.prototype.execute = function () {
  44622. };
  44623. DoNothingAction.prototype.serialize = function (parent) {
  44624. return _super.prototype._serialize.call(this, {
  44625. name: "DoNothingAction",
  44626. properties: []
  44627. }, parent);
  44628. };
  44629. return DoNothingAction;
  44630. }(BABYLON.Action));
  44631. BABYLON.DoNothingAction = DoNothingAction;
  44632. var CombineAction = /** @class */ (function (_super) {
  44633. __extends(CombineAction, _super);
  44634. function CombineAction(triggerOptions, children, condition) {
  44635. var _this = _super.call(this, triggerOptions, condition) || this;
  44636. _this.children = children;
  44637. return _this;
  44638. }
  44639. CombineAction.prototype._prepare = function () {
  44640. for (var index = 0; index < this.children.length; index++) {
  44641. this.children[index]._actionManager = this._actionManager;
  44642. this.children[index]._prepare();
  44643. }
  44644. };
  44645. CombineAction.prototype.execute = function (evt) {
  44646. for (var index = 0; index < this.children.length; index++) {
  44647. this.children[index].execute(evt);
  44648. }
  44649. };
  44650. CombineAction.prototype.serialize = function (parent) {
  44651. var serializationObject = _super.prototype._serialize.call(this, {
  44652. name: "CombineAction",
  44653. properties: [],
  44654. combine: []
  44655. }, parent);
  44656. for (var i = 0; i < this.children.length; i++) {
  44657. serializationObject.combine.push(this.children[i].serialize(null));
  44658. }
  44659. return serializationObject;
  44660. };
  44661. return CombineAction;
  44662. }(BABYLON.Action));
  44663. BABYLON.CombineAction = CombineAction;
  44664. var ExecuteCodeAction = /** @class */ (function (_super) {
  44665. __extends(ExecuteCodeAction, _super);
  44666. function ExecuteCodeAction(triggerOptions, func, condition) {
  44667. var _this = _super.call(this, triggerOptions, condition) || this;
  44668. _this.func = func;
  44669. return _this;
  44670. }
  44671. ExecuteCodeAction.prototype.execute = function (evt) {
  44672. this.func(evt);
  44673. };
  44674. return ExecuteCodeAction;
  44675. }(BABYLON.Action));
  44676. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  44677. var SetParentAction = /** @class */ (function (_super) {
  44678. __extends(SetParentAction, _super);
  44679. function SetParentAction(triggerOptions, target, parent, condition) {
  44680. var _this = _super.call(this, triggerOptions, condition) || this;
  44681. _this._target = target;
  44682. _this._parent = parent;
  44683. return _this;
  44684. }
  44685. SetParentAction.prototype._prepare = function () {
  44686. };
  44687. SetParentAction.prototype.execute = function () {
  44688. if (this._target.parent === this._parent) {
  44689. return;
  44690. }
  44691. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  44692. invertParentWorldMatrix.invert();
  44693. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  44694. this._target.parent = this._parent;
  44695. };
  44696. SetParentAction.prototype.serialize = function (parent) {
  44697. return _super.prototype._serialize.call(this, {
  44698. name: "SetParentAction",
  44699. properties: [
  44700. BABYLON.Action._GetTargetProperty(this._target),
  44701. BABYLON.Action._GetTargetProperty(this._parent),
  44702. ]
  44703. }, parent);
  44704. };
  44705. return SetParentAction;
  44706. }(BABYLON.Action));
  44707. BABYLON.SetParentAction = SetParentAction;
  44708. var PlaySoundAction = /** @class */ (function (_super) {
  44709. __extends(PlaySoundAction, _super);
  44710. function PlaySoundAction(triggerOptions, sound, condition) {
  44711. var _this = _super.call(this, triggerOptions, condition) || this;
  44712. _this._sound = sound;
  44713. return _this;
  44714. }
  44715. PlaySoundAction.prototype._prepare = function () {
  44716. };
  44717. PlaySoundAction.prototype.execute = function () {
  44718. if (this._sound !== undefined)
  44719. this._sound.play();
  44720. };
  44721. PlaySoundAction.prototype.serialize = function (parent) {
  44722. return _super.prototype._serialize.call(this, {
  44723. name: "PlaySoundAction",
  44724. properties: [{ name: "sound", value: this._sound.name }]
  44725. }, parent);
  44726. };
  44727. return PlaySoundAction;
  44728. }(BABYLON.Action));
  44729. BABYLON.PlaySoundAction = PlaySoundAction;
  44730. var StopSoundAction = /** @class */ (function (_super) {
  44731. __extends(StopSoundAction, _super);
  44732. function StopSoundAction(triggerOptions, sound, condition) {
  44733. var _this = _super.call(this, triggerOptions, condition) || this;
  44734. _this._sound = sound;
  44735. return _this;
  44736. }
  44737. StopSoundAction.prototype._prepare = function () {
  44738. };
  44739. StopSoundAction.prototype.execute = function () {
  44740. if (this._sound !== undefined)
  44741. this._sound.stop();
  44742. };
  44743. StopSoundAction.prototype.serialize = function (parent) {
  44744. return _super.prototype._serialize.call(this, {
  44745. name: "StopSoundAction",
  44746. properties: [{ name: "sound", value: this._sound.name }]
  44747. }, parent);
  44748. };
  44749. return StopSoundAction;
  44750. }(BABYLON.Action));
  44751. BABYLON.StopSoundAction = StopSoundAction;
  44752. })(BABYLON || (BABYLON = {}));
  44753. //# sourceMappingURL=babylon.directActions.js.map
  44754. var BABYLON;
  44755. (function (BABYLON) {
  44756. var SpriteManager = /** @class */ (function () {
  44757. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  44758. if (epsilon === void 0) { epsilon = 0.01; }
  44759. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44760. this.name = name;
  44761. this.sprites = new Array();
  44762. this.renderingGroupId = 0;
  44763. this.layerMask = 0x0FFFFFFF;
  44764. this.fogEnabled = true;
  44765. this.isPickable = false;
  44766. /**
  44767. * An event triggered when the manager is disposed.
  44768. * @type {BABYLON.Observable}
  44769. */
  44770. this.onDisposeObservable = new BABYLON.Observable();
  44771. this._vertexBuffers = {};
  44772. this._capacity = capacity;
  44773. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  44774. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44775. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44776. if (cellSize.width && cellSize.height) {
  44777. this.cellWidth = cellSize.width;
  44778. this.cellHeight = cellSize.height;
  44779. }
  44780. else if (cellSize !== undefined) {
  44781. this.cellWidth = cellSize;
  44782. this.cellHeight = cellSize;
  44783. }
  44784. else {
  44785. return;
  44786. }
  44787. this._epsilon = epsilon;
  44788. this._scene = scene;
  44789. this._scene.spriteManagers.push(this);
  44790. var indices = [];
  44791. var index = 0;
  44792. for (var count = 0; count < capacity; count++) {
  44793. indices.push(index);
  44794. indices.push(index + 1);
  44795. indices.push(index + 2);
  44796. indices.push(index);
  44797. indices.push(index + 2);
  44798. indices.push(index + 3);
  44799. index += 4;
  44800. }
  44801. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  44802. // VBO
  44803. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  44804. this._vertexData = new Float32Array(capacity * 16 * 4);
  44805. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  44806. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  44807. var options = this._buffer.createVertexBuffer("options", 4, 4);
  44808. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  44809. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  44810. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44811. this._vertexBuffers["options"] = options;
  44812. this._vertexBuffers["cellInfo"] = cellInfo;
  44813. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44814. // Effects
  44815. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  44816. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  44817. }
  44818. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  44819. set: function (callback) {
  44820. if (this._onDisposeObserver) {
  44821. this.onDisposeObservable.remove(this._onDisposeObserver);
  44822. }
  44823. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44824. },
  44825. enumerable: true,
  44826. configurable: true
  44827. });
  44828. Object.defineProperty(SpriteManager.prototype, "texture", {
  44829. get: function () {
  44830. return this._spriteTexture;
  44831. },
  44832. set: function (value) {
  44833. this._spriteTexture = value;
  44834. },
  44835. enumerable: true,
  44836. configurable: true
  44837. });
  44838. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  44839. var arrayOffset = index * 16;
  44840. if (offsetX === 0)
  44841. offsetX = this._epsilon;
  44842. else if (offsetX === 1)
  44843. offsetX = 1 - this._epsilon;
  44844. if (offsetY === 0)
  44845. offsetY = this._epsilon;
  44846. else if (offsetY === 1)
  44847. offsetY = 1 - this._epsilon;
  44848. this._vertexData[arrayOffset] = sprite.position.x;
  44849. this._vertexData[arrayOffset + 1] = sprite.position.y;
  44850. this._vertexData[arrayOffset + 2] = sprite.position.z;
  44851. this._vertexData[arrayOffset + 3] = sprite.angle;
  44852. this._vertexData[arrayOffset + 4] = sprite.width;
  44853. this._vertexData[arrayOffset + 5] = sprite.height;
  44854. this._vertexData[arrayOffset + 6] = offsetX;
  44855. this._vertexData[arrayOffset + 7] = offsetY;
  44856. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  44857. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  44858. var offset = (sprite.cellIndex / rowSize) >> 0;
  44859. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  44860. this._vertexData[arrayOffset + 11] = offset;
  44861. // Color
  44862. this._vertexData[arrayOffset + 12] = sprite.color.r;
  44863. this._vertexData[arrayOffset + 13] = sprite.color.g;
  44864. this._vertexData[arrayOffset + 14] = sprite.color.b;
  44865. this._vertexData[arrayOffset + 15] = sprite.color.a;
  44866. };
  44867. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  44868. var count = Math.min(this._capacity, this.sprites.length);
  44869. var min = BABYLON.Vector3.Zero();
  44870. var max = BABYLON.Vector3.Zero();
  44871. var distance = Number.MAX_VALUE;
  44872. var currentSprite = null;
  44873. var cameraSpacePosition = BABYLON.Vector3.Zero();
  44874. var cameraView = camera.getViewMatrix();
  44875. for (var index = 0; index < count; index++) {
  44876. var sprite = this.sprites[index];
  44877. if (!sprite) {
  44878. continue;
  44879. }
  44880. if (predicate) {
  44881. if (!predicate(sprite)) {
  44882. continue;
  44883. }
  44884. }
  44885. else if (!sprite.isPickable) {
  44886. continue;
  44887. }
  44888. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  44889. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  44890. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  44891. if (ray.intersectsBoxMinMax(min, max)) {
  44892. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  44893. if (distance > currentDistance) {
  44894. distance = currentDistance;
  44895. currentSprite = sprite;
  44896. if (fastCheck) {
  44897. break;
  44898. }
  44899. }
  44900. }
  44901. }
  44902. if (currentSprite) {
  44903. var result = new BABYLON.PickingInfo();
  44904. result.hit = true;
  44905. result.pickedSprite = currentSprite;
  44906. result.distance = distance;
  44907. return result;
  44908. }
  44909. return null;
  44910. };
  44911. SpriteManager.prototype.render = function () {
  44912. // Check
  44913. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  44914. return;
  44915. var engine = this._scene.getEngine();
  44916. var baseSize = this._spriteTexture.getBaseSize();
  44917. // Sprites
  44918. var deltaTime = engine.getDeltaTime();
  44919. var max = Math.min(this._capacity, this.sprites.length);
  44920. var rowSize = baseSize.width / this.cellWidth;
  44921. var offset = 0;
  44922. for (var index = 0; index < max; index++) {
  44923. var sprite = this.sprites[index];
  44924. if (!sprite) {
  44925. continue;
  44926. }
  44927. sprite._animate(deltaTime);
  44928. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  44929. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  44930. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  44931. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  44932. }
  44933. this._buffer.update(this._vertexData);
  44934. // Render
  44935. var effect = this._effectBase;
  44936. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44937. effect = this._effectFog;
  44938. }
  44939. engine.enableEffect(effect);
  44940. var viewMatrix = this._scene.getViewMatrix();
  44941. effect.setTexture("diffuseSampler", this._spriteTexture);
  44942. effect.setMatrix("view", viewMatrix);
  44943. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44944. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  44945. // Fog
  44946. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44947. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  44948. effect.setColor3("vFogColor", this._scene.fogColor);
  44949. }
  44950. // VBOs
  44951. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44952. // Draw order
  44953. engine.setDepthFunctionToLessOrEqual();
  44954. effect.setBool("alphaTest", true);
  44955. engine.setColorWrite(false);
  44956. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44957. engine.setColorWrite(true);
  44958. effect.setBool("alphaTest", false);
  44959. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44960. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44961. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44962. };
  44963. SpriteManager.prototype.dispose = function () {
  44964. if (this._buffer) {
  44965. this._buffer.dispose();
  44966. this._buffer = null;
  44967. }
  44968. if (this._indexBuffer) {
  44969. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44970. this._indexBuffer = null;
  44971. }
  44972. if (this._spriteTexture) {
  44973. this._spriteTexture.dispose();
  44974. this._spriteTexture = null;
  44975. }
  44976. // Remove from scene
  44977. var index = this._scene.spriteManagers.indexOf(this);
  44978. this._scene.spriteManagers.splice(index, 1);
  44979. // Callback
  44980. this.onDisposeObservable.notifyObservers(this);
  44981. this.onDisposeObservable.clear();
  44982. };
  44983. return SpriteManager;
  44984. }());
  44985. BABYLON.SpriteManager = SpriteManager;
  44986. })(BABYLON || (BABYLON = {}));
  44987. //# sourceMappingURL=babylon.spriteManager.js.map
  44988. var BABYLON;
  44989. (function (BABYLON) {
  44990. var Sprite = /** @class */ (function () {
  44991. function Sprite(name, manager) {
  44992. this.name = name;
  44993. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44994. this.width = 1.0;
  44995. this.height = 1.0;
  44996. this.angle = 0;
  44997. this.cellIndex = 0;
  44998. this.invertU = 0;
  44999. this.invertV = 0;
  45000. this.animations = new Array();
  45001. this.isPickable = false;
  45002. this._animationStarted = false;
  45003. this._loopAnimation = false;
  45004. this._fromIndex = 0;
  45005. this._toIndex = 0;
  45006. this._delay = 0;
  45007. this._direction = 1;
  45008. this._time = 0;
  45009. this._manager = manager;
  45010. this._manager.sprites.push(this);
  45011. this.position = BABYLON.Vector3.Zero();
  45012. }
  45013. Object.defineProperty(Sprite.prototype, "size", {
  45014. get: function () {
  45015. return this.width;
  45016. },
  45017. set: function (value) {
  45018. this.width = value;
  45019. this.height = value;
  45020. },
  45021. enumerable: true,
  45022. configurable: true
  45023. });
  45024. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  45025. this._fromIndex = from;
  45026. this._toIndex = to;
  45027. this._loopAnimation = loop;
  45028. this._delay = delay;
  45029. this._animationStarted = true;
  45030. this._direction = from < to ? 1 : -1;
  45031. this.cellIndex = from;
  45032. this._time = 0;
  45033. this._onAnimationEnd = onAnimationEnd;
  45034. };
  45035. Sprite.prototype.stopAnimation = function () {
  45036. this._animationStarted = false;
  45037. };
  45038. Sprite.prototype._animate = function (deltaTime) {
  45039. if (!this._animationStarted)
  45040. return;
  45041. this._time += deltaTime;
  45042. if (this._time > this._delay) {
  45043. this._time = this._time % this._delay;
  45044. this.cellIndex += this._direction;
  45045. if (this.cellIndex > this._toIndex) {
  45046. if (this._loopAnimation) {
  45047. this.cellIndex = this._fromIndex;
  45048. }
  45049. else {
  45050. this.cellIndex = this._toIndex;
  45051. this._animationStarted = false;
  45052. if (this._onAnimationEnd) {
  45053. this._onAnimationEnd();
  45054. }
  45055. if (this.disposeWhenFinishedAnimating) {
  45056. this.dispose();
  45057. }
  45058. }
  45059. }
  45060. }
  45061. };
  45062. Sprite.prototype.dispose = function () {
  45063. for (var i = 0; i < this._manager.sprites.length; i++) {
  45064. if (this._manager.sprites[i] == this) {
  45065. this._manager.sprites.splice(i, 1);
  45066. }
  45067. }
  45068. };
  45069. return Sprite;
  45070. }());
  45071. BABYLON.Sprite = Sprite;
  45072. })(BABYLON || (BABYLON = {}));
  45073. //# sourceMappingURL=babylon.sprite.js.map
  45074. var BABYLON;
  45075. (function (BABYLON) {
  45076. var IntersectionInfo = /** @class */ (function () {
  45077. function IntersectionInfo(bu, bv, distance) {
  45078. this.bu = bu;
  45079. this.bv = bv;
  45080. this.distance = distance;
  45081. this.faceId = 0;
  45082. this.subMeshId = 0;
  45083. }
  45084. return IntersectionInfo;
  45085. }());
  45086. BABYLON.IntersectionInfo = IntersectionInfo;
  45087. var PickingInfo = /** @class */ (function () {
  45088. function PickingInfo() {
  45089. this.hit = false;
  45090. this.distance = 0;
  45091. this.pickedPoint = null;
  45092. this.pickedMesh = null;
  45093. this.bu = 0;
  45094. this.bv = 0;
  45095. this.faceId = -1;
  45096. this.subMeshId = 0;
  45097. this.pickedSprite = null;
  45098. }
  45099. // Methods
  45100. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  45101. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  45102. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  45103. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45104. return null;
  45105. }
  45106. var indices = this.pickedMesh.getIndices();
  45107. if (!indices) {
  45108. return null;
  45109. }
  45110. var result;
  45111. if (useVerticesNormals) {
  45112. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45113. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  45114. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  45115. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  45116. normal0 = normal0.scale(this.bu);
  45117. normal1 = normal1.scale(this.bv);
  45118. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  45119. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  45120. }
  45121. else {
  45122. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45123. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  45124. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  45125. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  45126. var p1p2 = vertex1.subtract(vertex2);
  45127. var p3p2 = vertex3.subtract(vertex2);
  45128. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  45129. }
  45130. if (useWorldCoordinates) {
  45131. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  45132. }
  45133. return BABYLON.Vector3.Normalize(result);
  45134. };
  45135. PickingInfo.prototype.getTextureCoordinates = function () {
  45136. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45137. return null;
  45138. }
  45139. var indices = this.pickedMesh.getIndices();
  45140. if (!indices) {
  45141. return null;
  45142. }
  45143. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45144. if (!uvs) {
  45145. return null;
  45146. }
  45147. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  45148. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  45149. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  45150. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  45151. uv1 = uv1.scale(this.bu);
  45152. uv2 = uv2.scale(this.bv);
  45153. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  45154. };
  45155. return PickingInfo;
  45156. }());
  45157. BABYLON.PickingInfo = PickingInfo;
  45158. })(BABYLON || (BABYLON = {}));
  45159. //# sourceMappingURL=babylon.pickingInfo.js.map
  45160. var BABYLON;
  45161. (function (BABYLON) {
  45162. var Ray = /** @class */ (function () {
  45163. function Ray(origin, direction, length) {
  45164. if (length === void 0) { length = Number.MAX_VALUE; }
  45165. this.origin = origin;
  45166. this.direction = direction;
  45167. this.length = length;
  45168. }
  45169. // Methods
  45170. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  45171. var d = 0.0;
  45172. var maxValue = Number.MAX_VALUE;
  45173. var inv;
  45174. var min;
  45175. var max;
  45176. var temp;
  45177. if (Math.abs(this.direction.x) < 0.0000001) {
  45178. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  45179. return false;
  45180. }
  45181. }
  45182. else {
  45183. inv = 1.0 / this.direction.x;
  45184. min = (minimum.x - this.origin.x) * inv;
  45185. max = (maximum.x - this.origin.x) * inv;
  45186. if (max === -Infinity) {
  45187. max = Infinity;
  45188. }
  45189. if (min > max) {
  45190. temp = min;
  45191. min = max;
  45192. max = temp;
  45193. }
  45194. d = Math.max(min, d);
  45195. maxValue = Math.min(max, maxValue);
  45196. if (d > maxValue) {
  45197. return false;
  45198. }
  45199. }
  45200. if (Math.abs(this.direction.y) < 0.0000001) {
  45201. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  45202. return false;
  45203. }
  45204. }
  45205. else {
  45206. inv = 1.0 / this.direction.y;
  45207. min = (minimum.y - this.origin.y) * inv;
  45208. max = (maximum.y - this.origin.y) * inv;
  45209. if (max === -Infinity) {
  45210. max = Infinity;
  45211. }
  45212. if (min > max) {
  45213. temp = min;
  45214. min = max;
  45215. max = temp;
  45216. }
  45217. d = Math.max(min, d);
  45218. maxValue = Math.min(max, maxValue);
  45219. if (d > maxValue) {
  45220. return false;
  45221. }
  45222. }
  45223. if (Math.abs(this.direction.z) < 0.0000001) {
  45224. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  45225. return false;
  45226. }
  45227. }
  45228. else {
  45229. inv = 1.0 / this.direction.z;
  45230. min = (minimum.z - this.origin.z) * inv;
  45231. max = (maximum.z - this.origin.z) * inv;
  45232. if (max === -Infinity) {
  45233. max = Infinity;
  45234. }
  45235. if (min > max) {
  45236. temp = min;
  45237. min = max;
  45238. max = temp;
  45239. }
  45240. d = Math.max(min, d);
  45241. maxValue = Math.min(max, maxValue);
  45242. if (d > maxValue) {
  45243. return false;
  45244. }
  45245. }
  45246. return true;
  45247. };
  45248. Ray.prototype.intersectsBox = function (box) {
  45249. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  45250. };
  45251. Ray.prototype.intersectsSphere = function (sphere) {
  45252. var x = sphere.center.x - this.origin.x;
  45253. var y = sphere.center.y - this.origin.y;
  45254. var z = sphere.center.z - this.origin.z;
  45255. var pyth = (x * x) + (y * y) + (z * z);
  45256. var rr = sphere.radius * sphere.radius;
  45257. if (pyth <= rr) {
  45258. return true;
  45259. }
  45260. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  45261. if (dot < 0.0) {
  45262. return false;
  45263. }
  45264. var temp = pyth - (dot * dot);
  45265. return temp <= rr;
  45266. };
  45267. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  45268. if (!this._edge1) {
  45269. this._edge1 = BABYLON.Vector3.Zero();
  45270. this._edge2 = BABYLON.Vector3.Zero();
  45271. this._pvec = BABYLON.Vector3.Zero();
  45272. this._tvec = BABYLON.Vector3.Zero();
  45273. this._qvec = BABYLON.Vector3.Zero();
  45274. }
  45275. vertex1.subtractToRef(vertex0, this._edge1);
  45276. vertex2.subtractToRef(vertex0, this._edge2);
  45277. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  45278. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  45279. if (det === 0) {
  45280. return null;
  45281. }
  45282. var invdet = 1 / det;
  45283. this.origin.subtractToRef(vertex0, this._tvec);
  45284. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  45285. if (bu < 0 || bu > 1.0) {
  45286. return null;
  45287. }
  45288. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  45289. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  45290. if (bv < 0 || bu + bv > 1.0) {
  45291. return null;
  45292. }
  45293. //check if the distance is longer than the predefined length.
  45294. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  45295. if (distance > this.length) {
  45296. return null;
  45297. }
  45298. return new BABYLON.IntersectionInfo(bu, bv, distance);
  45299. };
  45300. Ray.prototype.intersectsPlane = function (plane) {
  45301. var distance;
  45302. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  45303. if (Math.abs(result1) < 9.99999997475243E-07) {
  45304. return null;
  45305. }
  45306. else {
  45307. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  45308. distance = (-plane.d - result2) / result1;
  45309. if (distance < 0.0) {
  45310. if (distance < -9.99999997475243E-07) {
  45311. return null;
  45312. }
  45313. else {
  45314. return 0;
  45315. }
  45316. }
  45317. return distance;
  45318. }
  45319. };
  45320. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  45321. var tm = BABYLON.Tmp.Matrix[0];
  45322. mesh.getWorldMatrix().invertToRef(tm);
  45323. if (this._tmpRay) {
  45324. Ray.TransformToRef(this, tm, this._tmpRay);
  45325. }
  45326. else {
  45327. this._tmpRay = Ray.Transform(this, tm);
  45328. }
  45329. return mesh.intersects(this._tmpRay, fastCheck);
  45330. };
  45331. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  45332. if (results) {
  45333. results.length = 0;
  45334. }
  45335. else {
  45336. results = [];
  45337. }
  45338. for (var i = 0; i < meshes.length; i++) {
  45339. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  45340. if (pickInfo.hit) {
  45341. results.push(pickInfo);
  45342. }
  45343. }
  45344. results.sort(this._comparePickingInfo);
  45345. return results;
  45346. };
  45347. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  45348. if (pickingInfoA.distance < pickingInfoB.distance) {
  45349. return -1;
  45350. }
  45351. else if (pickingInfoA.distance > pickingInfoB.distance) {
  45352. return 1;
  45353. }
  45354. else {
  45355. return 0;
  45356. }
  45357. };
  45358. /**
  45359. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  45360. * @param sega the first point of the segment to test the intersection against
  45361. * @param segb the second point of the segment to test the intersection against
  45362. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  45363. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  45364. */
  45365. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  45366. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  45367. var u = segb.subtract(sega);
  45368. var v = rsegb.subtract(this.origin);
  45369. var w = sega.subtract(this.origin);
  45370. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  45371. var b = BABYLON.Vector3.Dot(u, v);
  45372. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  45373. var d = BABYLON.Vector3.Dot(u, w);
  45374. var e = BABYLON.Vector3.Dot(v, w);
  45375. var D = a * c - b * b; // always >= 0
  45376. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  45377. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  45378. // compute the line parameters of the two closest points
  45379. if (D < Ray.smallnum) {
  45380. sN = 0.0; // force using point P0 on segment S1
  45381. sD = 1.0; // to prevent possible division by 0.0 later
  45382. tN = e;
  45383. tD = c;
  45384. }
  45385. else {
  45386. sN = (b * e - c * d);
  45387. tN = (a * e - b * d);
  45388. if (sN < 0.0) {
  45389. sN = 0.0;
  45390. tN = e;
  45391. tD = c;
  45392. }
  45393. else if (sN > sD) {
  45394. sN = sD;
  45395. tN = e + b;
  45396. tD = c;
  45397. }
  45398. }
  45399. if (tN < 0.0) {
  45400. tN = 0.0;
  45401. // recompute sc for this edge
  45402. if (-d < 0.0) {
  45403. sN = 0.0;
  45404. }
  45405. else if (-d > a)
  45406. sN = sD;
  45407. else {
  45408. sN = -d;
  45409. sD = a;
  45410. }
  45411. }
  45412. else if (tN > tD) {
  45413. tN = tD;
  45414. // recompute sc for this edge
  45415. if ((-d + b) < 0.0) {
  45416. sN = 0;
  45417. }
  45418. else if ((-d + b) > a) {
  45419. sN = sD;
  45420. }
  45421. else {
  45422. sN = (-d + b);
  45423. sD = a;
  45424. }
  45425. }
  45426. // finally do the division to get sc and tc
  45427. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  45428. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  45429. // get the difference of the two closest points
  45430. var qtc = v.multiplyByFloats(tc, tc, tc);
  45431. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  45432. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  45433. if (isIntersected) {
  45434. return qtc.length();
  45435. }
  45436. return -1;
  45437. };
  45438. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  45439. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  45440. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  45441. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  45442. this.direction.normalize();
  45443. return this;
  45444. };
  45445. // Statics
  45446. Ray.Zero = function () {
  45447. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  45448. };
  45449. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  45450. var result = Ray.Zero();
  45451. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  45452. };
  45453. /**
  45454. * 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
  45455. * transformed to the given world matrix.
  45456. * @param origin The origin point
  45457. * @param end The end point
  45458. * @param world a matrix to transform the ray to. Default is the identity matrix.
  45459. */
  45460. Ray.CreateNewFromTo = function (origin, end, world) {
  45461. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  45462. var direction = end.subtract(origin);
  45463. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  45464. direction.normalize();
  45465. return Ray.Transform(new Ray(origin, direction, length), world);
  45466. };
  45467. Ray.Transform = function (ray, matrix) {
  45468. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  45469. Ray.TransformToRef(ray, matrix, result);
  45470. return result;
  45471. };
  45472. Ray.TransformToRef = function (ray, matrix, result) {
  45473. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  45474. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  45475. result.length = ray.length;
  45476. var dir = result.direction;
  45477. var len = dir.length();
  45478. if (!(len === 0 || len === 1)) {
  45479. var num = 1.0 / len;
  45480. dir.x *= num;
  45481. dir.y *= num;
  45482. dir.z *= num;
  45483. result.length *= len;
  45484. }
  45485. };
  45486. Ray.smallnum = 0.00000001;
  45487. Ray.rayl = 10e8;
  45488. return Ray;
  45489. }());
  45490. BABYLON.Ray = Ray;
  45491. })(BABYLON || (BABYLON = {}));
  45492. //# sourceMappingURL=babylon.ray.js.map
  45493. var BABYLON;
  45494. (function (BABYLON) {
  45495. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  45496. if (boxMin.x > sphereCenter.x + sphereRadius)
  45497. return false;
  45498. if (sphereCenter.x - sphereRadius > boxMax.x)
  45499. return false;
  45500. if (boxMin.y > sphereCenter.y + sphereRadius)
  45501. return false;
  45502. if (sphereCenter.y - sphereRadius > boxMax.y)
  45503. return false;
  45504. if (boxMin.z > sphereCenter.z + sphereRadius)
  45505. return false;
  45506. if (sphereCenter.z - sphereRadius > boxMax.z)
  45507. return false;
  45508. return true;
  45509. };
  45510. var getLowestRoot = (function () {
  45511. var result = { root: 0, found: false };
  45512. return function (a, b, c, maxR) {
  45513. result.root = 0;
  45514. result.found = false;
  45515. var determinant = b * b - 4.0 * a * c;
  45516. if (determinant < 0)
  45517. return result;
  45518. var sqrtD = Math.sqrt(determinant);
  45519. var r1 = (-b - sqrtD) / (2.0 * a);
  45520. var r2 = (-b + sqrtD) / (2.0 * a);
  45521. if (r1 > r2) {
  45522. var temp = r2;
  45523. r2 = r1;
  45524. r1 = temp;
  45525. }
  45526. if (r1 > 0 && r1 < maxR) {
  45527. result.root = r1;
  45528. result.found = true;
  45529. return result;
  45530. }
  45531. if (r2 > 0 && r2 < maxR) {
  45532. result.root = r2;
  45533. result.found = true;
  45534. return result;
  45535. }
  45536. return result;
  45537. };
  45538. })();
  45539. var Collider = /** @class */ (function () {
  45540. function Collider() {
  45541. this._collisionPoint = BABYLON.Vector3.Zero();
  45542. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  45543. this._tempVector = BABYLON.Vector3.Zero();
  45544. this._tempVector2 = BABYLON.Vector3.Zero();
  45545. this._tempVector3 = BABYLON.Vector3.Zero();
  45546. this._tempVector4 = BABYLON.Vector3.Zero();
  45547. this._edge = BABYLON.Vector3.Zero();
  45548. this._baseToVertex = BABYLON.Vector3.Zero();
  45549. this._destinationPoint = BABYLON.Vector3.Zero();
  45550. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  45551. this._displacementVector = BABYLON.Vector3.Zero();
  45552. this._radius = BABYLON.Vector3.One();
  45553. this._retry = 0;
  45554. this._basePointWorld = BABYLON.Vector3.Zero();
  45555. this._velocityWorld = BABYLON.Vector3.Zero();
  45556. this._normalizedVelocity = BABYLON.Vector3.Zero();
  45557. this._collisionMask = -1;
  45558. }
  45559. Object.defineProperty(Collider.prototype, "collisionMask", {
  45560. get: function () {
  45561. return this._collisionMask;
  45562. },
  45563. set: function (mask) {
  45564. this._collisionMask = !isNaN(mask) ? mask : -1;
  45565. },
  45566. enumerable: true,
  45567. configurable: true
  45568. });
  45569. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  45570. /**
  45571. * Gets the plane normal used to compute the sliding response (in local space)
  45572. */
  45573. get: function () {
  45574. return this._slidePlaneNormal;
  45575. },
  45576. enumerable: true,
  45577. configurable: true
  45578. });
  45579. // Methods
  45580. Collider.prototype._initialize = function (source, dir, e) {
  45581. this._velocity = dir;
  45582. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  45583. this._basePoint = source;
  45584. source.multiplyToRef(this._radius, this._basePointWorld);
  45585. dir.multiplyToRef(this._radius, this._velocityWorld);
  45586. this._velocityWorldLength = this._velocityWorld.length();
  45587. this._epsilon = e;
  45588. this.collisionFound = false;
  45589. };
  45590. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  45591. pa.subtractToRef(point, this._tempVector);
  45592. pb.subtractToRef(point, this._tempVector2);
  45593. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  45594. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45595. if (d < 0)
  45596. return false;
  45597. pc.subtractToRef(point, this._tempVector3);
  45598. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  45599. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45600. if (d < 0)
  45601. return false;
  45602. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  45603. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45604. return d >= 0;
  45605. };
  45606. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  45607. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  45608. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  45609. if (distance > this._velocityWorldLength + max + sphereRadius) {
  45610. return false;
  45611. }
  45612. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  45613. return false;
  45614. return true;
  45615. };
  45616. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  45617. var t0;
  45618. var embeddedInPlane = false;
  45619. //defensive programming, actually not needed.
  45620. if (!trianglePlaneArray) {
  45621. trianglePlaneArray = [];
  45622. }
  45623. if (!trianglePlaneArray[faceIndex]) {
  45624. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  45625. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  45626. }
  45627. var trianglePlane = trianglePlaneArray[faceIndex];
  45628. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  45629. return;
  45630. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  45631. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  45632. if (normalDotVelocity == 0) {
  45633. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  45634. return;
  45635. embeddedInPlane = true;
  45636. t0 = 0;
  45637. }
  45638. else {
  45639. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45640. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45641. if (t0 > t1) {
  45642. var temp = t1;
  45643. t1 = t0;
  45644. t0 = temp;
  45645. }
  45646. if (t0 > 1.0 || t1 < 0.0)
  45647. return;
  45648. if (t0 < 0)
  45649. t0 = 0;
  45650. if (t0 > 1.0)
  45651. t0 = 1.0;
  45652. }
  45653. this._collisionPoint.copyFromFloats(0, 0, 0);
  45654. var found = false;
  45655. var t = 1.0;
  45656. if (!embeddedInPlane) {
  45657. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  45658. this._velocity.scaleToRef(t0, this._tempVector);
  45659. this._planeIntersectionPoint.addInPlace(this._tempVector);
  45660. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  45661. found = true;
  45662. t = t0;
  45663. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  45664. }
  45665. }
  45666. if (!found) {
  45667. var velocitySquaredLength = this._velocity.lengthSquared();
  45668. var a = velocitySquaredLength;
  45669. this._basePoint.subtractToRef(p1, this._tempVector);
  45670. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45671. var c = this._tempVector.lengthSquared() - 1.0;
  45672. var lowestRoot = getLowestRoot(a, b, c, t);
  45673. if (lowestRoot.found) {
  45674. t = lowestRoot.root;
  45675. found = true;
  45676. this._collisionPoint.copyFrom(p1);
  45677. }
  45678. this._basePoint.subtractToRef(p2, this._tempVector);
  45679. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45680. c = this._tempVector.lengthSquared() - 1.0;
  45681. lowestRoot = getLowestRoot(a, b, c, t);
  45682. if (lowestRoot.found) {
  45683. t = lowestRoot.root;
  45684. found = true;
  45685. this._collisionPoint.copyFrom(p2);
  45686. }
  45687. this._basePoint.subtractToRef(p3, this._tempVector);
  45688. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45689. c = this._tempVector.lengthSquared() - 1.0;
  45690. lowestRoot = getLowestRoot(a, b, c, t);
  45691. if (lowestRoot.found) {
  45692. t = lowestRoot.root;
  45693. found = true;
  45694. this._collisionPoint.copyFrom(p3);
  45695. }
  45696. p2.subtractToRef(p1, this._edge);
  45697. p1.subtractToRef(this._basePoint, this._baseToVertex);
  45698. var edgeSquaredLength = this._edge.lengthSquared();
  45699. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45700. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45701. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45702. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45703. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45704. lowestRoot = getLowestRoot(a, b, c, t);
  45705. if (lowestRoot.found) {
  45706. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45707. if (f >= 0.0 && f <= 1.0) {
  45708. t = lowestRoot.root;
  45709. found = true;
  45710. this._edge.scaleInPlace(f);
  45711. p1.addToRef(this._edge, this._collisionPoint);
  45712. }
  45713. }
  45714. p3.subtractToRef(p2, this._edge);
  45715. p2.subtractToRef(this._basePoint, this._baseToVertex);
  45716. edgeSquaredLength = this._edge.lengthSquared();
  45717. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45718. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45719. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45720. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45721. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45722. lowestRoot = getLowestRoot(a, b, c, t);
  45723. if (lowestRoot.found) {
  45724. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45725. if (f >= 0.0 && f <= 1.0) {
  45726. t = lowestRoot.root;
  45727. found = true;
  45728. this._edge.scaleInPlace(f);
  45729. p2.addToRef(this._edge, this._collisionPoint);
  45730. }
  45731. }
  45732. p1.subtractToRef(p3, this._edge);
  45733. p3.subtractToRef(this._basePoint, this._baseToVertex);
  45734. edgeSquaredLength = this._edge.lengthSquared();
  45735. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45736. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45737. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45738. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45739. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45740. lowestRoot = getLowestRoot(a, b, c, t);
  45741. if (lowestRoot.found) {
  45742. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45743. if (f >= 0.0 && f <= 1.0) {
  45744. t = lowestRoot.root;
  45745. found = true;
  45746. this._edge.scaleInPlace(f);
  45747. p3.addToRef(this._edge, this._collisionPoint);
  45748. }
  45749. }
  45750. }
  45751. if (found) {
  45752. var distToCollision = t * this._velocity.length();
  45753. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  45754. if (!this.intersectionPoint) {
  45755. this.intersectionPoint = this._collisionPoint.clone();
  45756. }
  45757. else {
  45758. this.intersectionPoint.copyFrom(this._collisionPoint);
  45759. }
  45760. this._nearestDistance = distToCollision;
  45761. this.collisionFound = true;
  45762. }
  45763. }
  45764. };
  45765. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  45766. for (var i = indexStart; i < indexEnd; i += 3) {
  45767. var p1 = pts[indices[i] - decal];
  45768. var p2 = pts[indices[i + 1] - decal];
  45769. var p3 = pts[indices[i + 2] - decal];
  45770. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  45771. }
  45772. };
  45773. Collider.prototype._getResponse = function (pos, vel) {
  45774. pos.addToRef(vel, this._destinationPoint);
  45775. vel.scaleInPlace((this._nearestDistance / vel.length()));
  45776. this._basePoint.addToRef(vel, pos);
  45777. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  45778. this._slidePlaneNormal.normalize();
  45779. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  45780. pos.addInPlace(this._displacementVector);
  45781. this.intersectionPoint.addInPlace(this._displacementVector);
  45782. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  45783. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  45784. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  45785. };
  45786. return Collider;
  45787. }());
  45788. BABYLON.Collider = Collider;
  45789. })(BABYLON || (BABYLON = {}));
  45790. //# sourceMappingURL=babylon.collider.js.map
  45791. var BABYLON;
  45792. (function (BABYLON) {
  45793. //WebWorker code will be inserted to this variable.
  45794. BABYLON.CollisionWorker = "";
  45795. var WorkerTaskType;
  45796. (function (WorkerTaskType) {
  45797. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  45798. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  45799. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  45800. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  45801. var WorkerReplyType;
  45802. (function (WorkerReplyType) {
  45803. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  45804. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  45805. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  45806. var CollisionCoordinatorWorker = /** @class */ (function () {
  45807. function CollisionCoordinatorWorker() {
  45808. var _this = this;
  45809. this._scaledPosition = BABYLON.Vector3.Zero();
  45810. this._scaledVelocity = BABYLON.Vector3.Zero();
  45811. this.onMeshUpdated = function (transformNode) {
  45812. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  45813. };
  45814. this.onGeometryUpdated = function (geometry) {
  45815. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  45816. };
  45817. this._afterRender = function () {
  45818. if (!_this._init)
  45819. return;
  45820. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  45821. return;
  45822. }
  45823. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  45824. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  45825. if (_this._runningUpdated > 4) {
  45826. return;
  45827. }
  45828. ++_this._runningUpdated;
  45829. var payload = {
  45830. updatedMeshes: _this._addUpdateMeshesList,
  45831. updatedGeometries: _this._addUpdateGeometriesList,
  45832. removedGeometries: _this._toRemoveGeometryArray,
  45833. removedMeshes: _this._toRemoveMeshesArray
  45834. };
  45835. var message = {
  45836. payload: payload,
  45837. taskType: WorkerTaskType.UPDATE
  45838. };
  45839. var serializable = [];
  45840. for (var id in payload.updatedGeometries) {
  45841. if (payload.updatedGeometries.hasOwnProperty(id)) {
  45842. //prepare transferables
  45843. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  45844. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  45845. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  45846. }
  45847. }
  45848. _this._worker.postMessage(message, serializable);
  45849. _this._addUpdateMeshesList = {};
  45850. _this._addUpdateGeometriesList = {};
  45851. _this._toRemoveGeometryArray = [];
  45852. _this._toRemoveMeshesArray = [];
  45853. };
  45854. this._onMessageFromWorker = function (e) {
  45855. var returnData = e.data;
  45856. if (returnData.error != WorkerReplyType.SUCCESS) {
  45857. //TODO what errors can be returned from the worker?
  45858. BABYLON.Tools.Warn("error returned from worker!");
  45859. return;
  45860. }
  45861. switch (returnData.taskType) {
  45862. case WorkerTaskType.INIT:
  45863. _this._init = true;
  45864. //Update the worked with ALL of the scene's current state
  45865. _this._scene.meshes.forEach(function (mesh) {
  45866. _this.onMeshAdded(mesh);
  45867. });
  45868. _this._scene.getGeometries().forEach(function (geometry) {
  45869. _this.onGeometryAdded(geometry);
  45870. });
  45871. break;
  45872. case WorkerTaskType.UPDATE:
  45873. _this._runningUpdated--;
  45874. break;
  45875. case WorkerTaskType.COLLIDE:
  45876. var returnPayload = returnData.payload;
  45877. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  45878. return;
  45879. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  45880. if (callback) {
  45881. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  45882. if (mesh) {
  45883. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  45884. }
  45885. }
  45886. //cleanup
  45887. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  45888. break;
  45889. }
  45890. };
  45891. this._collisionsCallbackArray = [];
  45892. this._init = false;
  45893. this._runningUpdated = 0;
  45894. this._addUpdateMeshesList = {};
  45895. this._addUpdateGeometriesList = {};
  45896. this._toRemoveGeometryArray = [];
  45897. this._toRemoveMeshesArray = [];
  45898. }
  45899. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45900. if (!this._init)
  45901. return;
  45902. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  45903. return;
  45904. position.divideToRef(collider._radius, this._scaledPosition);
  45905. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45906. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  45907. var payload = {
  45908. collider: {
  45909. position: this._scaledPosition.asArray(),
  45910. velocity: this._scaledVelocity.asArray(),
  45911. radius: collider._radius.asArray()
  45912. },
  45913. collisionId: collisionIndex,
  45914. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  45915. maximumRetry: maximumRetry
  45916. };
  45917. var message = {
  45918. payload: payload,
  45919. taskType: WorkerTaskType.COLLIDE
  45920. };
  45921. this._worker.postMessage(message);
  45922. };
  45923. CollisionCoordinatorWorker.prototype.init = function (scene) {
  45924. this._scene = scene;
  45925. this._scene.registerAfterRender(this._afterRender);
  45926. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  45927. this._worker = new Worker(workerUrl);
  45928. this._worker.onmessage = this._onMessageFromWorker;
  45929. var message = {
  45930. payload: {},
  45931. taskType: WorkerTaskType.INIT
  45932. };
  45933. this._worker.postMessage(message);
  45934. };
  45935. CollisionCoordinatorWorker.prototype.destroy = function () {
  45936. this._scene.unregisterAfterRender(this._afterRender);
  45937. this._worker.terminate();
  45938. };
  45939. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  45940. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  45941. this.onMeshUpdated(mesh);
  45942. };
  45943. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  45944. this._toRemoveMeshesArray.push(mesh.uniqueId);
  45945. };
  45946. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  45947. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  45948. geometry.onGeometryUpdated = this.onGeometryUpdated;
  45949. this.onGeometryUpdated(geometry);
  45950. };
  45951. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  45952. this._toRemoveGeometryArray.push(geometry.id);
  45953. };
  45954. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  45955. var submeshes = [];
  45956. if (mesh.subMeshes) {
  45957. submeshes = mesh.subMeshes.map(function (sm, idx) {
  45958. var boundingInfo = sm.getBoundingInfo();
  45959. return {
  45960. position: idx,
  45961. verticesStart: sm.verticesStart,
  45962. verticesCount: sm.verticesCount,
  45963. indexStart: sm.indexStart,
  45964. indexCount: sm.indexCount,
  45965. hasMaterial: !!sm.getMaterial(),
  45966. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45967. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45968. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45969. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  45970. };
  45971. });
  45972. }
  45973. var geometryId = null;
  45974. if (mesh instanceof BABYLON.Mesh) {
  45975. var geometry = mesh.geometry;
  45976. geometryId = geometry ? geometry.id : null;
  45977. }
  45978. else if (mesh instanceof BABYLON.InstancedMesh) {
  45979. var geometry = mesh.sourceMesh.geometry;
  45980. geometryId = geometry ? geometry.id : null;
  45981. }
  45982. var boundingInfo = mesh.getBoundingInfo();
  45983. return {
  45984. uniqueId: mesh.uniqueId,
  45985. id: mesh.id,
  45986. name: mesh.name,
  45987. geometryId: geometryId,
  45988. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45989. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45990. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45991. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  45992. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  45993. subMeshes: submeshes,
  45994. checkCollisions: mesh.checkCollisions
  45995. };
  45996. };
  45997. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  45998. return {
  45999. id: geometry.id,
  46000. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  46001. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  46002. indices: new Uint32Array(geometry.getIndices() || []),
  46003. };
  46004. };
  46005. return CollisionCoordinatorWorker;
  46006. }());
  46007. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  46008. var CollisionCoordinatorLegacy = /** @class */ (function () {
  46009. function CollisionCoordinatorLegacy() {
  46010. this._scaledPosition = BABYLON.Vector3.Zero();
  46011. this._scaledVelocity = BABYLON.Vector3.Zero();
  46012. this._finalPosition = BABYLON.Vector3.Zero();
  46013. }
  46014. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  46015. position.divideToRef(collider._radius, this._scaledPosition);
  46016. displacement.divideToRef(collider._radius, this._scaledVelocity);
  46017. collider.collidedMesh = null;
  46018. collider._retry = 0;
  46019. collider._initialVelocity = this._scaledVelocity;
  46020. collider._initialPosition = this._scaledPosition;
  46021. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  46022. this._finalPosition.multiplyInPlace(collider._radius);
  46023. //run the callback
  46024. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  46025. };
  46026. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  46027. this._scene = scene;
  46028. };
  46029. CollisionCoordinatorLegacy.prototype.destroy = function () {
  46030. //Legacy need no destruction method.
  46031. };
  46032. //No update in legacy mode
  46033. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  46034. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  46035. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  46036. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  46037. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  46038. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  46039. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  46040. if (excludedMesh === void 0) { excludedMesh = null; }
  46041. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  46042. if (collider._retry >= maximumRetry) {
  46043. finalPosition.copyFrom(position);
  46044. return;
  46045. }
  46046. // Check if this is a mesh else camera or -1
  46047. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  46048. collider._initialize(position, velocity, closeDistance);
  46049. // Check all meshes
  46050. for (var index = 0; index < this._scene.meshes.length; index++) {
  46051. var mesh = this._scene.meshes[index];
  46052. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  46053. mesh._checkCollision(collider);
  46054. }
  46055. }
  46056. if (!collider.collisionFound) {
  46057. position.addToRef(velocity, finalPosition);
  46058. return;
  46059. }
  46060. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  46061. collider._getResponse(position, velocity);
  46062. }
  46063. if (velocity.length() <= closeDistance) {
  46064. finalPosition.copyFrom(position);
  46065. return;
  46066. }
  46067. collider._retry++;
  46068. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  46069. };
  46070. return CollisionCoordinatorLegacy;
  46071. }());
  46072. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  46073. })(BABYLON || (BABYLON = {}));
  46074. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  46075. var BABYLON;
  46076. (function (BABYLON) {
  46077. var Particle = /** @class */ (function () {
  46078. function Particle(particleSystem) {
  46079. this.particleSystem = particleSystem;
  46080. this.position = BABYLON.Vector3.Zero();
  46081. this.direction = BABYLON.Vector3.Zero();
  46082. this.color = new BABYLON.Color4(0, 0, 0, 0);
  46083. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  46084. this.lifeTime = 1.0;
  46085. this.age = 0;
  46086. this.size = 0;
  46087. this.angle = 0;
  46088. this.angularSpeed = 0;
  46089. this._currentFrameCounter = 0;
  46090. this.cellIndex = 0;
  46091. if (!this.particleSystem.isAnimationSheetEnabled) {
  46092. return;
  46093. }
  46094. this.cellIndex = this.particleSystem.startSpriteCellID;
  46095. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  46096. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  46097. }
  46098. else {
  46099. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  46100. }
  46101. }
  46102. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  46103. // (ageOffset / scaledUpdateSpeed) / available cells
  46104. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  46105. this._currentFrameCounter += scaledUpdateSpeed;
  46106. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  46107. this._currentFrameCounter = 0;
  46108. this.cellIndex++;
  46109. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  46110. this.cellIndex = this.particleSystem.endSpriteCellID;
  46111. }
  46112. }
  46113. };
  46114. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  46115. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  46116. this.cellIndex++;
  46117. this._currentFrameCounter = 0;
  46118. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  46119. if (this.particleSystem.spriteCellLoop) {
  46120. this.cellIndex = this.particleSystem.startSpriteCellID;
  46121. }
  46122. else {
  46123. this.cellIndex = this.particleSystem.endSpriteCellID;
  46124. }
  46125. }
  46126. }
  46127. else {
  46128. this._currentFrameCounter++;
  46129. }
  46130. };
  46131. Particle.prototype.copyTo = function (other) {
  46132. other.position.copyFrom(this.position);
  46133. other.direction.copyFrom(this.direction);
  46134. other.color.copyFrom(this.color);
  46135. other.colorStep.copyFrom(this.colorStep);
  46136. other.lifeTime = this.lifeTime;
  46137. other.age = this.age;
  46138. other.size = this.size;
  46139. other.angle = this.angle;
  46140. other.angularSpeed = this.angularSpeed;
  46141. other.particleSystem = this.particleSystem;
  46142. other.cellIndex = this.cellIndex;
  46143. };
  46144. return Particle;
  46145. }());
  46146. BABYLON.Particle = Particle;
  46147. })(BABYLON || (BABYLON = {}));
  46148. //# sourceMappingURL=babylon.particle.js.map
  46149. var BABYLON;
  46150. (function (BABYLON) {
  46151. var ParticleSystem = /** @class */ (function () {
  46152. // end of sheet animation
  46153. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  46154. if (customEffect === void 0) { customEffect = null; }
  46155. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  46156. if (epsilon === void 0) { epsilon = 0.01; }
  46157. var _this = this;
  46158. this.name = name;
  46159. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  46160. // Members
  46161. this.animations = [];
  46162. this.renderingGroupId = 0;
  46163. this.emitter = null;
  46164. this.emitRate = 10;
  46165. this.manualEmitCount = -1;
  46166. this.updateSpeed = 0.01;
  46167. this.targetStopDuration = 0;
  46168. this.disposeOnStop = false;
  46169. this.minEmitPower = 1;
  46170. this.maxEmitPower = 1;
  46171. this.minLifeTime = 1;
  46172. this.maxLifeTime = 1;
  46173. this.minSize = 1;
  46174. this.maxSize = 1;
  46175. this.minAngularSpeed = 0;
  46176. this.maxAngularSpeed = 0;
  46177. this.layerMask = 0x0FFFFFFF;
  46178. this.customShader = null;
  46179. this.preventAutoStart = false;
  46180. /**
  46181. * An event triggered when the system is disposed.
  46182. * @type {BABYLON.Observable}
  46183. */
  46184. this.onDisposeObservable = new BABYLON.Observable();
  46185. this.onAnimationEnd = null;
  46186. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  46187. this.forceDepthWrite = false;
  46188. this.gravity = BABYLON.Vector3.Zero();
  46189. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  46190. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  46191. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  46192. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  46193. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46194. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46195. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  46196. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46197. this.particles = new Array();
  46198. this._stockParticles = new Array();
  46199. this._newPartsExcess = 0;
  46200. this._vertexBuffers = {};
  46201. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  46202. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  46203. this._scaledDirection = BABYLON.Vector3.Zero();
  46204. this._scaledGravity = BABYLON.Vector3.Zero();
  46205. this._currentRenderId = -1;
  46206. this._started = false;
  46207. this._stopped = false;
  46208. this._actualFrame = 0;
  46209. // sheet animation
  46210. this.startSpriteCellID = 0;
  46211. this.endSpriteCellID = 0;
  46212. this.spriteCellLoop = true;
  46213. this.spriteCellChangeSpeed = 0;
  46214. this.spriteCellWidth = 0;
  46215. this.spriteCellHeight = 0;
  46216. this._vertexBufferSize = 11;
  46217. this.appendParticleVertexes = null;
  46218. this.id = name;
  46219. this._capacity = capacity;
  46220. this._epsilon = epsilon;
  46221. if (_isAnimationSheetEnabled) {
  46222. this._vertexBufferSize = 12;
  46223. }
  46224. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46225. this._customEffect = customEffect;
  46226. scene.particleSystems.push(this);
  46227. this._createIndexBuffer();
  46228. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  46229. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  46230. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  46231. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  46232. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  46233. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  46234. if (this._isAnimationSheetEnabled) {
  46235. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  46236. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  46237. }
  46238. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  46239. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  46240. this._vertexBuffers["options"] = options;
  46241. // Default behaviors
  46242. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  46243. this.updateFunction = function (particles) {
  46244. for (var index = 0; index < particles.length; index++) {
  46245. var particle = particles[index];
  46246. particle.age += _this._scaledUpdateSpeed;
  46247. if (particle.age >= particle.lifeTime) {
  46248. _this.recycleParticle(particle);
  46249. index--;
  46250. continue;
  46251. }
  46252. else {
  46253. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  46254. particle.color.addInPlace(_this._scaledColorStep);
  46255. if (particle.color.a < 0)
  46256. particle.color.a = 0;
  46257. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  46258. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  46259. particle.position.addInPlace(_this._scaledDirection);
  46260. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  46261. particle.direction.addInPlace(_this._scaledGravity);
  46262. if (_this._isAnimationSheetEnabled) {
  46263. particle.updateCellIndex(_this._scaledUpdateSpeed);
  46264. }
  46265. }
  46266. }
  46267. };
  46268. }
  46269. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  46270. set: function (callback) {
  46271. if (this._onDisposeObserver) {
  46272. this.onDisposeObservable.remove(this._onDisposeObserver);
  46273. }
  46274. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  46275. },
  46276. enumerable: true,
  46277. configurable: true
  46278. });
  46279. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  46280. get: function () {
  46281. return this._isAnimationSheetEnabled;
  46282. },
  46283. enumerable: true,
  46284. configurable: true
  46285. });
  46286. ParticleSystem.prototype._createIndexBuffer = function () {
  46287. var indices = [];
  46288. var index = 0;
  46289. for (var count = 0; count < this._capacity; count++) {
  46290. indices.push(index);
  46291. indices.push(index + 1);
  46292. indices.push(index + 2);
  46293. indices.push(index);
  46294. indices.push(index + 2);
  46295. indices.push(index + 3);
  46296. index += 4;
  46297. }
  46298. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  46299. };
  46300. ParticleSystem.prototype.recycleParticle = function (particle) {
  46301. var lastParticle = this.particles.pop();
  46302. if (lastParticle !== particle) {
  46303. lastParticle.copyTo(particle);
  46304. this._stockParticles.push(lastParticle);
  46305. }
  46306. };
  46307. ParticleSystem.prototype.getCapacity = function () {
  46308. return this._capacity;
  46309. };
  46310. ParticleSystem.prototype.isAlive = function () {
  46311. return this._alive;
  46312. };
  46313. ParticleSystem.prototype.isStarted = function () {
  46314. return this._started;
  46315. };
  46316. ParticleSystem.prototype.start = function () {
  46317. this._started = true;
  46318. this._stopped = false;
  46319. this._actualFrame = 0;
  46320. };
  46321. ParticleSystem.prototype.stop = function () {
  46322. this._stopped = true;
  46323. };
  46324. // animation sheet
  46325. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  46326. var offset = index * this._vertexBufferSize;
  46327. this._vertexData[offset] = particle.position.x;
  46328. this._vertexData[offset + 1] = particle.position.y;
  46329. this._vertexData[offset + 2] = particle.position.z;
  46330. this._vertexData[offset + 3] = particle.color.r;
  46331. this._vertexData[offset + 4] = particle.color.g;
  46332. this._vertexData[offset + 5] = particle.color.b;
  46333. this._vertexData[offset + 6] = particle.color.a;
  46334. this._vertexData[offset + 7] = particle.angle;
  46335. this._vertexData[offset + 8] = particle.size;
  46336. this._vertexData[offset + 9] = offsetX;
  46337. this._vertexData[offset + 10] = offsetY;
  46338. };
  46339. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  46340. if (offsetX === 0)
  46341. offsetX = this._epsilon;
  46342. else if (offsetX === 1)
  46343. offsetX = 1 - this._epsilon;
  46344. if (offsetY === 0)
  46345. offsetY = this._epsilon;
  46346. else if (offsetY === 1)
  46347. offsetY = 1 - this._epsilon;
  46348. var offset = index * this._vertexBufferSize;
  46349. this._vertexData[offset] = particle.position.x;
  46350. this._vertexData[offset + 1] = particle.position.y;
  46351. this._vertexData[offset + 2] = particle.position.z;
  46352. this._vertexData[offset + 3] = particle.color.r;
  46353. this._vertexData[offset + 4] = particle.color.g;
  46354. this._vertexData[offset + 5] = particle.color.b;
  46355. this._vertexData[offset + 6] = particle.color.a;
  46356. this._vertexData[offset + 7] = particle.angle;
  46357. this._vertexData[offset + 8] = particle.size;
  46358. this._vertexData[offset + 9] = offsetX;
  46359. this._vertexData[offset + 10] = offsetY;
  46360. this._vertexData[offset + 11] = particle.cellIndex;
  46361. };
  46362. ParticleSystem.prototype._update = function (newParticles) {
  46363. // Update current
  46364. this._alive = this.particles.length > 0;
  46365. this.updateFunction(this.particles);
  46366. // Add new ones
  46367. var worldMatrix;
  46368. if (this.emitter.position) {
  46369. var emitterMesh = this.emitter;
  46370. worldMatrix = emitterMesh.getWorldMatrix();
  46371. }
  46372. else {
  46373. var emitterPosition = this.emitter;
  46374. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  46375. }
  46376. var particle;
  46377. for (var index = 0; index < newParticles; index++) {
  46378. if (this.particles.length === this._capacity) {
  46379. break;
  46380. }
  46381. if (this._stockParticles.length !== 0) {
  46382. particle = this._stockParticles.pop();
  46383. particle.age = 0;
  46384. particle.cellIndex = this.startSpriteCellID;
  46385. }
  46386. else {
  46387. particle = new BABYLON.Particle(this);
  46388. }
  46389. this.particles.push(particle);
  46390. var emitPower = ParticleSystem.randomNumber(this.minEmitPower, this.maxEmitPower);
  46391. if (this.startDirectionFunction) {
  46392. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  46393. }
  46394. else {
  46395. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  46396. }
  46397. if (this.startPositionFunction) {
  46398. this.startPositionFunction(worldMatrix, particle.position, particle);
  46399. }
  46400. else {
  46401. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  46402. }
  46403. particle.lifeTime = ParticleSystem.randomNumber(this.minLifeTime, this.maxLifeTime);
  46404. particle.size = ParticleSystem.randomNumber(this.minSize, this.maxSize);
  46405. particle.angularSpeed = ParticleSystem.randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  46406. var step = ParticleSystem.randomNumber(0, 1.0);
  46407. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  46408. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  46409. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  46410. }
  46411. };
  46412. ParticleSystem.prototype._getEffect = function () {
  46413. if (this._customEffect) {
  46414. return this._customEffect;
  46415. }
  46416. ;
  46417. var defines = [];
  46418. if (this._scene.clipPlane) {
  46419. defines.push("#define CLIPPLANE");
  46420. }
  46421. if (this._isAnimationSheetEnabled) {
  46422. defines.push("#define ANIMATESHEET");
  46423. }
  46424. // Effect
  46425. var join = defines.join("\n");
  46426. if (this._cachedDefines !== join) {
  46427. this._cachedDefines = join;
  46428. var attributesNamesOrOptions;
  46429. var effectCreationOption;
  46430. if (this._isAnimationSheetEnabled) {
  46431. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  46432. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  46433. }
  46434. else {
  46435. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  46436. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  46437. }
  46438. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  46439. }
  46440. return this._effect;
  46441. };
  46442. ParticleSystem.prototype.animate = function () {
  46443. if (!this._started)
  46444. return;
  46445. var effect = this._getEffect();
  46446. // Check
  46447. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  46448. return;
  46449. if (this._currentRenderId === this._scene.getRenderId()) {
  46450. return;
  46451. }
  46452. this._currentRenderId = this._scene.getRenderId();
  46453. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  46454. // determine the number of particles we need to create
  46455. var newParticles;
  46456. if (this.manualEmitCount > -1) {
  46457. newParticles = this.manualEmitCount;
  46458. this._newPartsExcess = 0;
  46459. this.manualEmitCount = 0;
  46460. }
  46461. else {
  46462. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  46463. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  46464. }
  46465. if (this._newPartsExcess > 1.0) {
  46466. newParticles += this._newPartsExcess >> 0;
  46467. this._newPartsExcess -= this._newPartsExcess >> 0;
  46468. }
  46469. this._alive = false;
  46470. if (!this._stopped) {
  46471. this._actualFrame += this._scaledUpdateSpeed;
  46472. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  46473. this.stop();
  46474. }
  46475. else {
  46476. newParticles = 0;
  46477. }
  46478. this._update(newParticles);
  46479. // Stopped?
  46480. if (this._stopped) {
  46481. if (!this._alive) {
  46482. this._started = false;
  46483. if (this.onAnimationEnd) {
  46484. this.onAnimationEnd();
  46485. }
  46486. if (this.disposeOnStop) {
  46487. this._scene._toBeDisposed.push(this);
  46488. }
  46489. }
  46490. }
  46491. // Animation sheet
  46492. if (this._isAnimationSheetEnabled) {
  46493. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  46494. }
  46495. else {
  46496. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  46497. }
  46498. // Update VBO
  46499. var offset = 0;
  46500. for (var index = 0; index < this.particles.length; index++) {
  46501. var particle = this.particles[index];
  46502. this.appendParticleVertexes(offset, particle);
  46503. offset += 4;
  46504. }
  46505. if (this._vertexBuffer) {
  46506. this._vertexBuffer.update(this._vertexData);
  46507. }
  46508. };
  46509. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  46510. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  46511. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  46512. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  46513. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  46514. };
  46515. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  46516. this._appendParticleVertex(offset++, particle, 0, 0);
  46517. this._appendParticleVertex(offset++, particle, 1, 0);
  46518. this._appendParticleVertex(offset++, particle, 1, 1);
  46519. this._appendParticleVertex(offset++, particle, 0, 1);
  46520. };
  46521. ParticleSystem.prototype.rebuild = function () {
  46522. this._createIndexBuffer();
  46523. if (this._vertexBuffer) {
  46524. this._vertexBuffer._rebuild();
  46525. }
  46526. };
  46527. ParticleSystem.prototype.render = function () {
  46528. var effect = this._getEffect();
  46529. // Check
  46530. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  46531. return 0;
  46532. var engine = this._scene.getEngine();
  46533. // Render
  46534. engine.enableEffect(effect);
  46535. engine.setState(false);
  46536. var viewMatrix = this._scene.getViewMatrix();
  46537. effect.setTexture("diffuseSampler", this.particleTexture);
  46538. effect.setMatrix("view", viewMatrix);
  46539. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46540. if (this._isAnimationSheetEnabled) {
  46541. var baseSize = this.particleTexture.getBaseSize();
  46542. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  46543. }
  46544. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  46545. if (this._scene.clipPlane) {
  46546. var clipPlane = this._scene.clipPlane;
  46547. var invView = viewMatrix.clone();
  46548. invView.invert();
  46549. effect.setMatrix("invView", invView);
  46550. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  46551. }
  46552. // VBOs
  46553. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46554. // Draw order
  46555. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  46556. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  46557. }
  46558. else {
  46559. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46560. }
  46561. if (this.forceDepthWrite) {
  46562. engine.setDepthWrite(true);
  46563. }
  46564. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this.particles.length * 6);
  46565. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46566. return this.particles.length;
  46567. };
  46568. ParticleSystem.prototype.dispose = function () {
  46569. if (this._vertexBuffer) {
  46570. this._vertexBuffer.dispose();
  46571. this._vertexBuffer = null;
  46572. }
  46573. if (this._indexBuffer) {
  46574. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46575. this._indexBuffer = null;
  46576. }
  46577. if (this.particleTexture) {
  46578. this.particleTexture.dispose();
  46579. this.particleTexture = null;
  46580. }
  46581. // Remove from scene
  46582. var index = this._scene.particleSystems.indexOf(this);
  46583. if (index > -1) {
  46584. this._scene.particleSystems.splice(index, 1);
  46585. }
  46586. // Callback
  46587. this.onDisposeObservable.notifyObservers(this);
  46588. this.onDisposeObservable.clear();
  46589. };
  46590. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  46591. if (radius === void 0) { radius = 1; }
  46592. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  46593. this.particleEmitterType = particleEmitter;
  46594. return particleEmitter;
  46595. };
  46596. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  46597. if (radius === void 0) { radius = 1; }
  46598. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  46599. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  46600. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  46601. this.particleEmitterType = particleEmitter;
  46602. return particleEmitter;
  46603. };
  46604. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  46605. if (radius === void 0) { radius = 1; }
  46606. if (angle === void 0) { angle = Math.PI / 4; }
  46607. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  46608. this.particleEmitterType = particleEmitter;
  46609. return particleEmitter;
  46610. };
  46611. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  46612. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  46613. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  46614. this.direction1 = direction1;
  46615. this.direction2 = direction2;
  46616. this.minEmitBox = minEmitBox;
  46617. this.maxEmitBox = maxEmitBox;
  46618. this.particleEmitterType = particleEmitter;
  46619. return particleEmitter;
  46620. };
  46621. ParticleSystem.randomNumber = function (min, max) {
  46622. if (min === max) {
  46623. return (min);
  46624. }
  46625. var random = Math.random();
  46626. return ((random * (max - min)) + min);
  46627. };
  46628. // Clone
  46629. ParticleSystem.prototype.clone = function (name, newEmitter) {
  46630. var custom = null;
  46631. var program = null;
  46632. if (this.customShader != null) {
  46633. program = this.customShader;
  46634. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46635. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46636. }
  46637. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  46638. result.customShader = program;
  46639. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  46640. if (newEmitter === undefined) {
  46641. newEmitter = this.emitter;
  46642. }
  46643. result.emitter = newEmitter;
  46644. if (this.particleTexture) {
  46645. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  46646. }
  46647. if (!this.preventAutoStart) {
  46648. result.start();
  46649. }
  46650. return result;
  46651. };
  46652. ParticleSystem.prototype.serialize = function () {
  46653. var serializationObject = {};
  46654. serializationObject.name = this.name;
  46655. serializationObject.id = this.id;
  46656. // Emitter
  46657. if (this.emitter.position) {
  46658. var emitterMesh = this.emitter;
  46659. serializationObject.emitterId = emitterMesh.id;
  46660. }
  46661. else {
  46662. var emitterPosition = this.emitter;
  46663. serializationObject.emitter = emitterPosition.asArray();
  46664. }
  46665. serializationObject.capacity = this.getCapacity();
  46666. if (this.particleTexture) {
  46667. serializationObject.textureName = this.particleTexture.name;
  46668. }
  46669. // Animations
  46670. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  46671. // Particle system
  46672. serializationObject.minAngularSpeed = this.minAngularSpeed;
  46673. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  46674. serializationObject.minSize = this.minSize;
  46675. serializationObject.maxSize = this.maxSize;
  46676. serializationObject.minEmitPower = this.minEmitPower;
  46677. serializationObject.maxEmitPower = this.maxEmitPower;
  46678. serializationObject.minLifeTime = this.minLifeTime;
  46679. serializationObject.maxLifeTime = this.maxLifeTime;
  46680. serializationObject.emitRate = this.emitRate;
  46681. serializationObject.minEmitBox = this.minEmitBox.asArray();
  46682. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  46683. serializationObject.gravity = this.gravity.asArray();
  46684. serializationObject.direction1 = this.direction1.asArray();
  46685. serializationObject.direction2 = this.direction2.asArray();
  46686. serializationObject.color1 = this.color1.asArray();
  46687. serializationObject.color2 = this.color2.asArray();
  46688. serializationObject.colorDead = this.colorDead.asArray();
  46689. serializationObject.updateSpeed = this.updateSpeed;
  46690. serializationObject.targetStopDuration = this.targetStopDuration;
  46691. serializationObject.textureMask = this.textureMask.asArray();
  46692. serializationObject.blendMode = this.blendMode;
  46693. serializationObject.customShader = this.customShader;
  46694. serializationObject.preventAutoStart = this.preventAutoStart;
  46695. serializationObject.startSpriteCellID = this.startSpriteCellID;
  46696. serializationObject.endSpriteCellID = this.endSpriteCellID;
  46697. serializationObject.spriteCellLoop = this.spriteCellLoop;
  46698. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  46699. serializationObject.spriteCellWidth = this.spriteCellWidth;
  46700. serializationObject.spriteCellHeight = this.spriteCellHeight;
  46701. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  46702. return serializationObject;
  46703. };
  46704. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  46705. var name = parsedParticleSystem.name;
  46706. var custom = null;
  46707. var program = null;
  46708. if (parsedParticleSystem.customShader) {
  46709. program = parsedParticleSystem.customShader;
  46710. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46711. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46712. }
  46713. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  46714. particleSystem.customShader = program;
  46715. if (parsedParticleSystem.id) {
  46716. particleSystem.id = parsedParticleSystem.id;
  46717. }
  46718. // Auto start
  46719. if (parsedParticleSystem.preventAutoStart) {
  46720. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  46721. }
  46722. // Texture
  46723. if (parsedParticleSystem.textureName) {
  46724. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  46725. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  46726. }
  46727. // Emitter
  46728. if (parsedParticleSystem.emitterId) {
  46729. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  46730. }
  46731. else {
  46732. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  46733. }
  46734. // Animations
  46735. if (parsedParticleSystem.animations) {
  46736. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  46737. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  46738. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  46739. }
  46740. }
  46741. if (parsedParticleSystem.autoAnimate) {
  46742. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  46743. }
  46744. // Particle system
  46745. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  46746. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  46747. particleSystem.minSize = parsedParticleSystem.minSize;
  46748. particleSystem.maxSize = parsedParticleSystem.maxSize;
  46749. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  46750. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  46751. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  46752. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  46753. particleSystem.emitRate = parsedParticleSystem.emitRate;
  46754. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  46755. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  46756. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  46757. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  46758. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  46759. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  46760. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  46761. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  46762. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  46763. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  46764. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  46765. particleSystem.blendMode = parsedParticleSystem.blendMode;
  46766. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  46767. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  46768. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  46769. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  46770. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  46771. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  46772. if (!particleSystem.preventAutoStart) {
  46773. particleSystem.start();
  46774. }
  46775. return particleSystem;
  46776. };
  46777. // Statics
  46778. ParticleSystem.BLENDMODE_ONEONE = 0;
  46779. ParticleSystem.BLENDMODE_STANDARD = 1;
  46780. return ParticleSystem;
  46781. }());
  46782. BABYLON.ParticleSystem = ParticleSystem;
  46783. })(BABYLON || (BABYLON = {}));
  46784. //# sourceMappingURL=babylon.particleSystem.js.map
  46785. var BABYLON;
  46786. (function (BABYLON) {
  46787. var BoxParticleEmitter = /** @class */ (function () {
  46788. // to be updated like the rest of emitters when breaking changes.
  46789. // all property should be come public variables and passed through constructor.
  46790. function BoxParticleEmitter(_particleSystem) {
  46791. this._particleSystem = _particleSystem;
  46792. }
  46793. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  46794. get: function () {
  46795. return this._particleSystem.direction1;
  46796. },
  46797. set: function (value) {
  46798. this._particleSystem.direction1 = value;
  46799. },
  46800. enumerable: true,
  46801. configurable: true
  46802. });
  46803. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  46804. get: function () {
  46805. return this._particleSystem.direction2;
  46806. },
  46807. set: function (value) {
  46808. this._particleSystem.direction2 = value;
  46809. },
  46810. enumerable: true,
  46811. configurable: true
  46812. });
  46813. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  46814. get: function () {
  46815. return this._particleSystem.minEmitBox;
  46816. },
  46817. set: function (value) {
  46818. this._particleSystem.minEmitBox = value;
  46819. },
  46820. enumerable: true,
  46821. configurable: true
  46822. });
  46823. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  46824. get: function () {
  46825. return this._particleSystem.maxEmitBox;
  46826. },
  46827. set: function (value) {
  46828. this._particleSystem.maxEmitBox = value;
  46829. },
  46830. enumerable: true,
  46831. configurable: true
  46832. });
  46833. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46834. var randX = BABYLON.ParticleSystem.randomNumber(this.direction1.x, this.direction2.x);
  46835. var randY = BABYLON.ParticleSystem.randomNumber(this.direction1.y, this.direction2.y);
  46836. var randZ = BABYLON.ParticleSystem.randomNumber(this.direction1.z, this.direction2.z);
  46837. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46838. };
  46839. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46840. var randX = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.x, this.maxEmitBox.x);
  46841. var randY = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.y, this.maxEmitBox.y);
  46842. var randZ = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.z, this.maxEmitBox.z);
  46843. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  46844. };
  46845. return BoxParticleEmitter;
  46846. }());
  46847. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  46848. })(BABYLON || (BABYLON = {}));
  46849. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  46850. var BABYLON;
  46851. (function (BABYLON) {
  46852. var ConeParticleEmitter = /** @class */ (function () {
  46853. function ConeParticleEmitter(radius, angle) {
  46854. this.radius = radius;
  46855. this.angle = angle;
  46856. }
  46857. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46858. if (this.angle === 0) {
  46859. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  46860. }
  46861. else {
  46862. var phi = BABYLON.ParticleSystem.randomNumber(0, 2 * Math.PI);
  46863. var theta = BABYLON.ParticleSystem.randomNumber(0, this.angle);
  46864. var randX = Math.cos(phi) * Math.sin(theta);
  46865. var randY = Math.cos(theta);
  46866. var randZ = Math.sin(phi) * Math.sin(theta);
  46867. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46868. }
  46869. };
  46870. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46871. var s = BABYLON.ParticleSystem.randomNumber(0, Math.PI * 2);
  46872. var radius = BABYLON.ParticleSystem.randomNumber(0, this.radius);
  46873. var randX = radius * Math.sin(s);
  46874. var randZ = radius * Math.cos(s);
  46875. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, 0, randZ, worldMatrix, positionToUpdate);
  46876. };
  46877. return ConeParticleEmitter;
  46878. }());
  46879. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  46880. })(BABYLON || (BABYLON = {}));
  46881. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  46882. var BABYLON;
  46883. (function (BABYLON) {
  46884. var SphereParticleEmitter = /** @class */ (function () {
  46885. function SphereParticleEmitter(radius) {
  46886. this.radius = radius;
  46887. }
  46888. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46889. // measure the direction Vector from the emitter to the particle.
  46890. var direction = particle.position.subtract(worldMatrix.getTranslation());
  46891. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  46892. };
  46893. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46894. var phi = BABYLON.ParticleSystem.randomNumber(0, 2 * Math.PI);
  46895. var theta = BABYLON.ParticleSystem.randomNumber(0, Math.PI);
  46896. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  46897. var randY = this.radius * Math.cos(theta);
  46898. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  46899. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  46900. };
  46901. return SphereParticleEmitter;
  46902. }());
  46903. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  46904. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  46905. __extends(SphereDirectedParticleEmitter, _super);
  46906. function SphereDirectedParticleEmitter(radius, direction1, direction2) {
  46907. var _this = _super.call(this, radius) || this;
  46908. _this.direction1 = direction1;
  46909. _this.direction2 = direction2;
  46910. return _this;
  46911. }
  46912. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46913. var randX = BABYLON.ParticleSystem.randomNumber(this.direction1.x, this.direction2.x);
  46914. var randY = BABYLON.ParticleSystem.randomNumber(this.direction1.y, this.direction2.y);
  46915. var randZ = BABYLON.ParticleSystem.randomNumber(this.direction1.z, this.direction2.z);
  46916. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46917. };
  46918. return SphereDirectedParticleEmitter;
  46919. }(SphereParticleEmitter));
  46920. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  46921. })(BABYLON || (BABYLON = {}));
  46922. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  46923. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  46924. var BABYLON;
  46925. (function (BABYLON) {
  46926. var GPUParticleSystem = /** @class */ (function () {
  46927. function GPUParticleSystem(name, capacity, scene) {
  46928. this.name = name;
  46929. this.emitter = null;
  46930. this.renderingGroupId = 0;
  46931. this.layerMask = 0x0FFFFFFF; // TODO
  46932. this._updateVertexBuffers = {};
  46933. this._renderVertexBuffers = {};
  46934. this._currentRenderId = -1;
  46935. this._started = true;
  46936. /**
  46937. * An event triggered when the system is disposed.
  46938. * @type {BABYLON.Observable}
  46939. */
  46940. this.onDisposeObservable = new BABYLON.Observable();
  46941. this.id = name;
  46942. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46943. this._capacity = capacity;
  46944. this._engine = this._scene.getEngine();
  46945. this._scene.particleSystems.push(this);
  46946. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "velocity"], [], [], this._scene.getEngine());
  46947. var updateEffectOptions = {
  46948. attributes: ["position", "age", "life", "velocity"],
  46949. uniformsNames: [],
  46950. uniformBuffersNames: [],
  46951. samplers: [],
  46952. defines: "",
  46953. fallbacks: null,
  46954. onCompiled: null,
  46955. onError: null,
  46956. indexParameters: null,
  46957. maxSimultaneousLights: 0,
  46958. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outVelocity"]
  46959. };
  46960. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", updateEffectOptions, this._scene.getEngine());
  46961. }
  46962. GPUParticleSystem.prototype.isStarted = function () {
  46963. return this._started;
  46964. };
  46965. GPUParticleSystem.prototype.start = function () {
  46966. this._started = true;
  46967. };
  46968. GPUParticleSystem.prototype.stop = function () {
  46969. this._started = false;
  46970. };
  46971. GPUParticleSystem.prototype.animate = function () {
  46972. // Do nothing
  46973. };
  46974. GPUParticleSystem.prototype._initialize = function () {
  46975. if (this._renderVAO) {
  46976. return;
  46977. }
  46978. var data = new Array();
  46979. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  46980. // position
  46981. data.push(0.0);
  46982. data.push(0.0);
  46983. data.push(0.0);
  46984. var life = 1 + Math.random() * 10; // TODO: var
  46985. data.push(life + 1); // create the particle as a dead one to create a new one at start
  46986. data.push(life);
  46987. // velocity
  46988. data.push(0.0);
  46989. data.push(0.0);
  46990. data.push(0.0);
  46991. }
  46992. // Update VAO
  46993. this._updateBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  46994. this._updateVertexBuffers["position"] = this._updateBuffer.createVertexBuffer("position", 0, 3, 3);
  46995. this._updateVertexBuffers["age"] = this._updateBuffer.createVertexBuffer("age", 3, 1, 1);
  46996. this._updateVertexBuffers["life"] = this._updateBuffer.createVertexBuffer("life", 4, 1, 1);
  46997. this._updateVertexBuffers["velocity"] = this._updateBuffer.createVertexBuffer("velocity", 5, 3, 3);
  46998. this._updateVAO = this._engine.recordVertexArrayObject(this._updateVertexBuffers, null, this._updateEffect);
  46999. this._engine.bindArrayBuffer(null);
  47000. // Render VAO
  47001. this._renderBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  47002. this._renderVertexBuffers["position"] = this._renderBuffer.createVertexBuffer("position", 0, 3, 3);
  47003. this._renderVertexBuffers["age"] = this._renderBuffer.createVertexBuffer("age", 3, 1, 1);
  47004. this._renderVertexBuffers["life"] = this._renderBuffer.createVertexBuffer("life", 4, 1, 1);
  47005. this._renderVertexBuffers["velocity"] = this._renderBuffer.createVertexBuffer("velocity", 5, 3, 3);
  47006. this._renderVAO = this._engine.recordVertexArrayObject(this._renderVertexBuffers, null, this._renderEffect);
  47007. this._engine.bindArrayBuffer(null);
  47008. // Links
  47009. this._sourceVAO = this._updateVAO;
  47010. this._targetVAO = this._renderVAO;
  47011. this._sourceBuffer = this._updateBuffer;
  47012. this._targetBuffer = this._renderBuffer;
  47013. };
  47014. GPUParticleSystem.prototype.render = function () {
  47015. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  47016. return 0;
  47017. }
  47018. // Get everything ready to render
  47019. this._initialize();
  47020. if (this._currentRenderId === this._scene.getRenderId()) {
  47021. return 0;
  47022. }
  47023. this._currentRenderId = this._scene.getRenderId();
  47024. // Enable update effect
  47025. this._engine.enableEffect(this._updateEffect);
  47026. this._engine.setState(false);
  47027. // Bind source VAO
  47028. this._engine.bindVertexArrayObject(this._sourceVAO, null);
  47029. // Update
  47030. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  47031. this._engine.setRasterizerState(false);
  47032. this._engine.beginTransformFeedback();
  47033. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  47034. this._engine.endTransformFeedback();
  47035. this._engine.setRasterizerState(true);
  47036. this._engine.bindTransformFeedbackBuffer(null);
  47037. // Enable render effect
  47038. this._engine.enableEffect(this._renderEffect);
  47039. // Bind source VAO
  47040. this._engine.bindVertexArrayObject(this._targetVAO, null);
  47041. // Render
  47042. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  47043. // Switch VAOs
  47044. var tmpVAO = this._sourceVAO;
  47045. this._sourceVAO = this._targetVAO;
  47046. this._targetVAO = tmpVAO;
  47047. // Switch buffers
  47048. var tmpBuffer = this._sourceBuffer;
  47049. this._sourceBuffer = this._targetBuffer;
  47050. this._targetBuffer = tmpBuffer;
  47051. return 0;
  47052. };
  47053. GPUParticleSystem.prototype.rebuild = function () {
  47054. };
  47055. GPUParticleSystem.prototype.dispose = function () {
  47056. var index = this._scene.particleSystems.indexOf(this);
  47057. if (index > -1) {
  47058. this._scene.particleSystems.splice(index, 1);
  47059. }
  47060. //TODO: this._dataBuffer.dispose();
  47061. // Callback
  47062. this.onDisposeObservable.notifyObservers(this);
  47063. this.onDisposeObservable.clear();
  47064. };
  47065. //TODO: Clone / Parse / serialize
  47066. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  47067. return null;
  47068. };
  47069. GPUParticleSystem.prototype.serialize = function () {
  47070. };
  47071. return GPUParticleSystem;
  47072. }());
  47073. BABYLON.GPUParticleSystem = GPUParticleSystem;
  47074. })(BABYLON || (BABYLON = {}));
  47075. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  47076. var BABYLON;
  47077. (function (BABYLON) {
  47078. var SolidParticle = /** @class */ (function () {
  47079. /**
  47080. * Creates a Solid Particle object.
  47081. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  47082. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  47083. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  47084. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  47085. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  47086. * `shapeId` (integer) is the model shape identifier in the SPS.
  47087. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  47088. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  47089. */
  47090. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  47091. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  47092. this.idx = 0; // particle global index
  47093. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  47094. this.position = BABYLON.Vector3.Zero(); // position
  47095. this.rotation = BABYLON.Vector3.Zero(); // rotation
  47096. this.scaling = BABYLON.Vector3.One(); // scaling
  47097. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  47098. this.velocity = BABYLON.Vector3.Zero(); // velocity
  47099. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  47100. this.alive = true; // alive
  47101. this.isVisible = true; // visibility
  47102. this._pos = 0; // index of this particle in the global "positions" array
  47103. this._ind = 0; // index of this particle in the global "indices" array
  47104. this.shapeId = 0; // model shape id
  47105. this.idxInShape = 0; // index of the particle in its shape id
  47106. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  47107. this.idx = particleIndex;
  47108. this._pos = positionIndex;
  47109. this._ind = indiceIndex;
  47110. this._model = model;
  47111. this.shapeId = shapeId;
  47112. this.idxInShape = idxInShape;
  47113. this._sps = sps;
  47114. if (modelBoundingInfo) {
  47115. this._modelBoundingInfo = modelBoundingInfo;
  47116. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  47117. }
  47118. }
  47119. Object.defineProperty(SolidParticle.prototype, "scale", {
  47120. /**
  47121. * legacy support, changed scale to scaling
  47122. */
  47123. get: function () {
  47124. return this.scaling;
  47125. },
  47126. set: function (scale) {
  47127. this.scaling = scale;
  47128. },
  47129. enumerable: true,
  47130. configurable: true
  47131. });
  47132. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  47133. /**
  47134. * legacy support, changed quaternion to rotationQuaternion
  47135. */
  47136. get: function () {
  47137. return this.rotationQuaternion;
  47138. },
  47139. set: function (q) {
  47140. this.rotationQuaternion = q;
  47141. },
  47142. enumerable: true,
  47143. configurable: true
  47144. });
  47145. /**
  47146. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  47147. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  47148. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  47149. */
  47150. SolidParticle.prototype.intersectsMesh = function (target) {
  47151. if (!this._boundingInfo || !target._boundingInfo) {
  47152. return false;
  47153. }
  47154. if (this._sps._bSphereOnly) {
  47155. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  47156. }
  47157. return this._boundingInfo.intersects(target._boundingInfo, false);
  47158. };
  47159. return SolidParticle;
  47160. }());
  47161. BABYLON.SolidParticle = SolidParticle;
  47162. var ModelShape = /** @class */ (function () {
  47163. /**
  47164. * 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.
  47165. * SPS internal tool, don't use it manually.
  47166. */
  47167. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  47168. this._indicesLength = 0; // length of the shape in the model indices array
  47169. this.shapeID = id;
  47170. this._shape = shape;
  47171. this._indicesLength = indicesLength;
  47172. this._shapeUV = shapeUV;
  47173. this._positionFunction = posFunction;
  47174. this._vertexFunction = vtxFunction;
  47175. }
  47176. return ModelShape;
  47177. }());
  47178. BABYLON.ModelShape = ModelShape;
  47179. var DepthSortedParticle = /** @class */ (function () {
  47180. function DepthSortedParticle() {
  47181. this.ind = 0; // index of the particle in the "indices" array
  47182. this.indicesLength = 0; // length of the particle shape in the "indices" array
  47183. this.sqDistance = 0.0; // squared distance from the particle to the camera
  47184. }
  47185. return DepthSortedParticle;
  47186. }());
  47187. BABYLON.DepthSortedParticle = DepthSortedParticle;
  47188. })(BABYLON || (BABYLON = {}));
  47189. //# sourceMappingURL=babylon.solidParticle.js.map
  47190. var BABYLON;
  47191. (function (BABYLON) {
  47192. /**
  47193. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  47194. */
  47195. var SolidParticleSystem = /** @class */ (function () {
  47196. /**
  47197. * Creates a SPS (Solid Particle System) object.
  47198. * `name` (String) is the SPS name, this will be the underlying mesh name.
  47199. * `scene` (Scene) is the scene in which the SPS is added.
  47200. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  47201. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  47202. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  47203. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  47204. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  47205. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  47206. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  47207. */
  47208. function SolidParticleSystem(name, scene, options) {
  47209. // public members
  47210. /**
  47211. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  47212. * Example : var p = SPS.particles[i];
  47213. */
  47214. this.particles = new Array();
  47215. /**
  47216. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  47217. */
  47218. this.nbParticles = 0;
  47219. /**
  47220. * If the particles must ever face the camera (default false). Useful for planar particles.
  47221. */
  47222. this.billboard = false;
  47223. /**
  47224. * Recompute normals when adding a shape
  47225. */
  47226. this.recomputeNormals = true;
  47227. /**
  47228. * This a counter ofr your own usage. It's not set by any SPS functions.
  47229. */
  47230. this.counter = 0;
  47231. /**
  47232. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  47233. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  47234. */
  47235. this.vars = {};
  47236. this._positions = new Array();
  47237. this._indices = new Array();
  47238. this._normals = new Array();
  47239. this._colors = new Array();
  47240. this._uvs = new Array();
  47241. this._index = 0; // indices index
  47242. this._updatable = true;
  47243. this._pickable = false;
  47244. this._isVisibilityBoxLocked = false;
  47245. this._alwaysVisible = false;
  47246. this._depthSort = false;
  47247. this._shapeCounter = 0;
  47248. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  47249. this._color = new BABYLON.Color4(0, 0, 0, 0);
  47250. this._computeParticleColor = true;
  47251. this._computeParticleTexture = true;
  47252. this._computeParticleRotation = true;
  47253. this._computeParticleVertex = false;
  47254. this._computeBoundingBox = false;
  47255. this._depthSortParticles = true;
  47256. this._cam_axisZ = BABYLON.Vector3.Zero();
  47257. this._cam_axisY = BABYLON.Vector3.Zero();
  47258. this._cam_axisX = BABYLON.Vector3.Zero();
  47259. this._axisZ = BABYLON.Axis.Z;
  47260. this._camDir = BABYLON.Vector3.Zero();
  47261. this._camInvertedPosition = BABYLON.Vector3.Zero();
  47262. this._rotMatrix = new BABYLON.Matrix();
  47263. this._invertMatrix = new BABYLON.Matrix();
  47264. this._rotated = BABYLON.Vector3.Zero();
  47265. this._quaternion = new BABYLON.Quaternion();
  47266. this._vertex = BABYLON.Vector3.Zero();
  47267. this._normal = BABYLON.Vector3.Zero();
  47268. this._yaw = 0.0;
  47269. this._pitch = 0.0;
  47270. this._roll = 0.0;
  47271. this._halfroll = 0.0;
  47272. this._halfpitch = 0.0;
  47273. this._halfyaw = 0.0;
  47274. this._sinRoll = 0.0;
  47275. this._cosRoll = 0.0;
  47276. this._sinPitch = 0.0;
  47277. this._cosPitch = 0.0;
  47278. this._sinYaw = 0.0;
  47279. this._cosYaw = 0.0;
  47280. this._mustUnrotateFixedNormals = false;
  47281. this._minimum = BABYLON.Tmp.Vector3[0];
  47282. this._maximum = BABYLON.Tmp.Vector3[1];
  47283. this._minBbox = BABYLON.Tmp.Vector3[4];
  47284. this._maxBbox = BABYLON.Tmp.Vector3[5];
  47285. this._particlesIntersect = false;
  47286. this._depthSortFunction = function (p1, p2) {
  47287. return (p2.sqDistance - p1.sqDistance);
  47288. };
  47289. this._needs32Bits = false;
  47290. this._bSphereOnly = false;
  47291. this._bSphereRadiusFactor = 1.0;
  47292. this.name = name;
  47293. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47294. this._camera = scene.activeCamera;
  47295. this._pickable = options ? options.isPickable : false;
  47296. this._depthSort = options ? options.enableDepthSort : false;
  47297. this._particlesIntersect = options ? options.particleIntersection : false;
  47298. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  47299. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  47300. if (options && options.updatable) {
  47301. this._updatable = options.updatable;
  47302. }
  47303. else {
  47304. this._updatable = true;
  47305. }
  47306. if (this._pickable) {
  47307. this.pickedParticles = [];
  47308. }
  47309. if (this._depthSort) {
  47310. this.depthSortedParticles = [];
  47311. }
  47312. }
  47313. /**
  47314. * Builds the SPS underlying mesh. Returns a standard Mesh.
  47315. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  47316. */
  47317. SolidParticleSystem.prototype.buildMesh = function () {
  47318. if (this.nbParticles === 0) {
  47319. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  47320. this.addShape(triangle, 1);
  47321. triangle.dispose();
  47322. }
  47323. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  47324. this._positions32 = new Float32Array(this._positions);
  47325. this._uvs32 = new Float32Array(this._uvs);
  47326. this._colors32 = new Float32Array(this._colors);
  47327. if (this.recomputeNormals) {
  47328. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  47329. }
  47330. this._normals32 = new Float32Array(this._normals);
  47331. this._fixedNormal32 = new Float32Array(this._normals);
  47332. if (this._mustUnrotateFixedNormals) {
  47333. this._unrotateFixedNormals();
  47334. }
  47335. var vertexData = new BABYLON.VertexData();
  47336. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  47337. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  47338. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  47339. if (this._uvs32) {
  47340. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  47341. ;
  47342. }
  47343. if (this._colors32) {
  47344. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  47345. }
  47346. var mesh = new BABYLON.Mesh(this.name, this._scene);
  47347. vertexData.applyToMesh(mesh, this._updatable);
  47348. this.mesh = mesh;
  47349. this.mesh.isPickable = this._pickable;
  47350. // free memory
  47351. if (!this._depthSort) {
  47352. this._indices = null;
  47353. }
  47354. this._positions = null;
  47355. this._normals = null;
  47356. this._uvs = null;
  47357. this._colors = null;
  47358. if (!this._updatable) {
  47359. this.particles.length = 0;
  47360. }
  47361. return mesh;
  47362. };
  47363. /**
  47364. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  47365. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  47366. * Thus the particles generated from `digest()` have their property `position` set yet.
  47367. * `mesh` ( Mesh ) is the mesh to be digested
  47368. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  47369. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  47370. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  47371. */
  47372. SolidParticleSystem.prototype.digest = function (mesh, options) {
  47373. var size = (options && options.facetNb) || 1;
  47374. var number = (options && options.number) || 0;
  47375. var delta = (options && options.delta) || 0;
  47376. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47377. var meshInd = mesh.getIndices();
  47378. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47379. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47380. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47381. var f = 0; // facet counter
  47382. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  47383. // compute size from number
  47384. if (number) {
  47385. number = (number > totalFacets) ? totalFacets : number;
  47386. size = Math.round(totalFacets / number);
  47387. delta = 0;
  47388. }
  47389. else {
  47390. size = (size > totalFacets) ? totalFacets : size;
  47391. }
  47392. var facetPos = []; // submesh positions
  47393. var facetInd = []; // submesh indices
  47394. var facetUV = []; // submesh UV
  47395. var facetCol = []; // submesh colors
  47396. var barycenter = BABYLON.Tmp.Vector3[0];
  47397. var sizeO = size;
  47398. while (f < totalFacets) {
  47399. size = sizeO + Math.floor((1 + delta) * Math.random());
  47400. if (f > totalFacets - size) {
  47401. size = totalFacets - f;
  47402. }
  47403. // reset temp arrays
  47404. facetPos.length = 0;
  47405. facetInd.length = 0;
  47406. facetUV.length = 0;
  47407. facetCol.length = 0;
  47408. // iterate over "size" facets
  47409. var fi = 0;
  47410. for (var j = f * 3; j < (f + size) * 3; j++) {
  47411. facetInd.push(fi);
  47412. var i = meshInd[j];
  47413. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  47414. if (meshUV) {
  47415. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  47416. }
  47417. if (meshCol) {
  47418. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  47419. }
  47420. fi++;
  47421. }
  47422. // create a model shape for each single particle
  47423. var idx = this.nbParticles;
  47424. var shape = this._posToShape(facetPos);
  47425. var shapeUV = this._uvsToShapeUV(facetUV);
  47426. // compute the barycenter of the shape
  47427. var v;
  47428. for (v = 0; v < shape.length; v++) {
  47429. barycenter.addInPlace(shape[v]);
  47430. }
  47431. barycenter.scaleInPlace(1 / shape.length);
  47432. // shift the shape from its barycenter to the origin
  47433. for (v = 0; v < shape.length; v++) {
  47434. shape[v].subtractInPlace(barycenter);
  47435. }
  47436. var bInfo;
  47437. if (this._particlesIntersect) {
  47438. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  47439. }
  47440. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  47441. // add the particle in the SPS
  47442. var currentPos = this._positions.length;
  47443. var currentInd = this._indices.length;
  47444. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  47445. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  47446. // initialize the particle position
  47447. this.particles[this.nbParticles].position.addInPlace(barycenter);
  47448. this._index += shape.length;
  47449. idx++;
  47450. this.nbParticles++;
  47451. this._shapeCounter++;
  47452. f += size;
  47453. }
  47454. return this;
  47455. };
  47456. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  47457. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  47458. var index = 0;
  47459. var idx = 0;
  47460. for (var p = 0; p < this.particles.length; p++) {
  47461. this._particle = this.particles[p];
  47462. this._shape = this._particle._model._shape;
  47463. if (this._particle.rotationQuaternion) {
  47464. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47465. }
  47466. else {
  47467. this._yaw = this._particle.rotation.y;
  47468. this._pitch = this._particle.rotation.x;
  47469. this._roll = this._particle.rotation.z;
  47470. this._quaternionRotationYPR();
  47471. }
  47472. this._quaternionToRotationMatrix();
  47473. this._rotMatrix.invertToRef(this._invertMatrix);
  47474. for (var pt = 0; pt < this._shape.length; pt++) {
  47475. idx = index + pt * 3;
  47476. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  47477. this._fixedNormal32[idx] = this._normal.x;
  47478. this._fixedNormal32[idx + 1] = this._normal.y;
  47479. this._fixedNormal32[idx + 2] = this._normal.z;
  47480. }
  47481. index = idx + 3;
  47482. }
  47483. };
  47484. //reset copy
  47485. SolidParticleSystem.prototype._resetCopy = function () {
  47486. this._copy.position.x = 0;
  47487. this._copy.position.y = 0;
  47488. this._copy.position.z = 0;
  47489. this._copy.rotation.x = 0;
  47490. this._copy.rotation.y = 0;
  47491. this._copy.rotation.z = 0;
  47492. this._copy.rotationQuaternion = null;
  47493. this._copy.scaling.x = 1.0;
  47494. this._copy.scaling.y = 1.0;
  47495. this._copy.scaling.z = 1.0;
  47496. this._copy.uvs.x = 0;
  47497. this._copy.uvs.y = 0;
  47498. this._copy.uvs.z = 1.0;
  47499. this._copy.uvs.w = 1.0;
  47500. this._copy.color = null;
  47501. };
  47502. // _meshBuilder : inserts the shape model in the global SPS mesh
  47503. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  47504. var i;
  47505. var u = 0;
  47506. var c = 0;
  47507. var n = 0;
  47508. this._resetCopy();
  47509. if (options && options.positionFunction) {
  47510. options.positionFunction(this._copy, idx, idxInShape);
  47511. this._mustUnrotateFixedNormals = true;
  47512. }
  47513. if (this._copy.rotationQuaternion) {
  47514. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47515. }
  47516. else {
  47517. this._yaw = this._copy.rotation.y;
  47518. this._pitch = this._copy.rotation.x;
  47519. this._roll = this._copy.rotation.z;
  47520. this._quaternionRotationYPR();
  47521. }
  47522. this._quaternionToRotationMatrix();
  47523. for (i = 0; i < shape.length; i++) {
  47524. this._vertex.x = shape[i].x;
  47525. this._vertex.y = shape[i].y;
  47526. this._vertex.z = shape[i].z;
  47527. if (options && options.vertexFunction) {
  47528. options.vertexFunction(this._copy, this._vertex, i);
  47529. }
  47530. this._vertex.x *= this._copy.scaling.x;
  47531. this._vertex.y *= this._copy.scaling.y;
  47532. this._vertex.z *= this._copy.scaling.z;
  47533. this._vertex.x += this._copy.pivot.x;
  47534. this._vertex.y += this._copy.pivot.y;
  47535. this._vertex.z += this._copy.pivot.z;
  47536. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47537. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  47538. if (meshUV) {
  47539. 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);
  47540. u += 2;
  47541. }
  47542. if (this._copy.color) {
  47543. this._color = this._copy.color;
  47544. }
  47545. else if (meshCol && meshCol[c] !== undefined) {
  47546. this._color.r = meshCol[c];
  47547. this._color.g = meshCol[c + 1];
  47548. this._color.b = meshCol[c + 2];
  47549. this._color.a = meshCol[c + 3];
  47550. }
  47551. else {
  47552. this._color.r = 1.0;
  47553. this._color.g = 1.0;
  47554. this._color.b = 1.0;
  47555. this._color.a = 1.0;
  47556. }
  47557. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  47558. c += 4;
  47559. if (!this.recomputeNormals && meshNor) {
  47560. this._normal.x = meshNor[n];
  47561. this._normal.y = meshNor[n + 1];
  47562. this._normal.z = meshNor[n + 2];
  47563. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  47564. normals.push(this._normal.x, this._normal.y, this._normal.z);
  47565. n += 3;
  47566. }
  47567. }
  47568. for (i = 0; i < meshInd.length; i++) {
  47569. var current_ind = p + meshInd[i];
  47570. indices.push(current_ind);
  47571. if (current_ind > 65535) {
  47572. this._needs32Bits = true;
  47573. }
  47574. }
  47575. if (this._pickable) {
  47576. var nbfaces = meshInd.length / 3;
  47577. for (i = 0; i < nbfaces; i++) {
  47578. this.pickedParticles.push({ idx: idx, faceId: i });
  47579. }
  47580. }
  47581. if (this._depthSort) {
  47582. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  47583. }
  47584. return this._copy;
  47585. };
  47586. // returns a shape array from positions array
  47587. SolidParticleSystem.prototype._posToShape = function (positions) {
  47588. var shape = [];
  47589. for (var i = 0; i < positions.length; i += 3) {
  47590. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  47591. }
  47592. return shape;
  47593. };
  47594. // returns a shapeUV array from a Vector4 uvs
  47595. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  47596. var shapeUV = [];
  47597. if (uvs) {
  47598. for (var i = 0; i < uvs.length; i++)
  47599. shapeUV.push(uvs[i]);
  47600. }
  47601. return shapeUV;
  47602. };
  47603. // adds a new particle object in the particles array
  47604. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  47605. if (bInfo === void 0) { bInfo = null; }
  47606. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  47607. this.particles.push(sp);
  47608. return sp;
  47609. };
  47610. /**
  47611. * Adds some particles to the SPS from the model shape. Returns the shape id.
  47612. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  47613. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  47614. * `nb` (positive integer) the number of particles to be created from this model
  47615. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  47616. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  47617. */
  47618. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  47619. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47620. var meshInd = mesh.getIndices();
  47621. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47622. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47623. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47624. var bbInfo;
  47625. if (this._particlesIntersect) {
  47626. bbInfo = mesh.getBoundingInfo();
  47627. }
  47628. var shape = this._posToShape(meshPos);
  47629. var shapeUV = this._uvsToShapeUV(meshUV);
  47630. var posfunc = options ? options.positionFunction : null;
  47631. var vtxfunc = options ? options.vertexFunction : null;
  47632. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  47633. // particles
  47634. var sp;
  47635. var currentCopy;
  47636. var idx = this.nbParticles;
  47637. for (var i = 0; i < nb; i++) {
  47638. var currentPos = this._positions.length;
  47639. var currentInd = this._indices.length;
  47640. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  47641. if (this._updatable) {
  47642. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  47643. sp.position.copyFrom(currentCopy.position);
  47644. sp.rotation.copyFrom(currentCopy.rotation);
  47645. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  47646. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  47647. }
  47648. if (currentCopy.color && sp.color) {
  47649. sp.color.copyFrom(currentCopy.color);
  47650. }
  47651. sp.scaling.copyFrom(currentCopy.scaling);
  47652. sp.uvs.copyFrom(currentCopy.uvs);
  47653. }
  47654. this._index += shape.length;
  47655. idx++;
  47656. }
  47657. this.nbParticles += nb;
  47658. this._shapeCounter++;
  47659. return this._shapeCounter - 1;
  47660. };
  47661. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  47662. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  47663. this._resetCopy();
  47664. if (particle._model._positionFunction) {
  47665. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  47666. }
  47667. if (this._copy.rotationQuaternion) {
  47668. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47669. }
  47670. else {
  47671. this._yaw = this._copy.rotation.y;
  47672. this._pitch = this._copy.rotation.x;
  47673. this._roll = this._copy.rotation.z;
  47674. this._quaternionRotationYPR();
  47675. }
  47676. this._quaternionToRotationMatrix();
  47677. this._shape = particle._model._shape;
  47678. for (var pt = 0; pt < this._shape.length; pt++) {
  47679. this._vertex.x = this._shape[pt].x;
  47680. this._vertex.y = this._shape[pt].y;
  47681. this._vertex.z = this._shape[pt].z;
  47682. if (particle._model._vertexFunction) {
  47683. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  47684. }
  47685. this._vertex.x *= this._copy.scaling.x;
  47686. this._vertex.y *= this._copy.scaling.y;
  47687. this._vertex.z *= this._copy.scaling.z;
  47688. this._vertex.x += this._copy.pivot.x;
  47689. this._vertex.y += this._copy.pivot.y;
  47690. this._vertex.z += this._copy.pivot.z;
  47691. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47692. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  47693. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  47694. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  47695. }
  47696. particle.position.x = 0.0;
  47697. particle.position.y = 0.0;
  47698. particle.position.z = 0.0;
  47699. particle.rotation.x = 0.0;
  47700. particle.rotation.y = 0.0;
  47701. particle.rotation.z = 0.0;
  47702. particle.rotationQuaternion = null;
  47703. particle.scaling.x = 1.0;
  47704. particle.scaling.y = 1.0;
  47705. particle.scaling.z = 1.0;
  47706. };
  47707. /**
  47708. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  47709. * Returns the SPS.
  47710. */
  47711. SolidParticleSystem.prototype.rebuildMesh = function () {
  47712. for (var p = 0; p < this.particles.length; p++) {
  47713. this._rebuildParticle(this.particles[p]);
  47714. }
  47715. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47716. return this;
  47717. };
  47718. /**
  47719. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  47720. * This method calls `updateParticle()` for each particle of the SPS.
  47721. * For an animated SPS, it is usually called within the render loop.
  47722. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  47723. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  47724. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  47725. * Returns the SPS.
  47726. */
  47727. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  47728. if (start === void 0) { start = 0; }
  47729. if (end === void 0) { end = this.nbParticles - 1; }
  47730. if (update === void 0) { update = true; }
  47731. if (!this._updatable) {
  47732. return this;
  47733. }
  47734. // custom beforeUpdate
  47735. this.beforeUpdateParticles(start, end, update);
  47736. this._cam_axisX.x = 1.0;
  47737. this._cam_axisX.y = 0.0;
  47738. this._cam_axisX.z = 0.0;
  47739. this._cam_axisY.x = 0.0;
  47740. this._cam_axisY.y = 1.0;
  47741. this._cam_axisY.z = 0.0;
  47742. this._cam_axisZ.x = 0.0;
  47743. this._cam_axisZ.y = 0.0;
  47744. this._cam_axisZ.z = 1.0;
  47745. // cases when the World Matrix is to be computed first
  47746. if (this.billboard || this._depthSort) {
  47747. this.mesh.computeWorldMatrix(true);
  47748. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  47749. }
  47750. // if the particles will always face the camera
  47751. if (this.billboard) {
  47752. // compute the camera position and un-rotate it by the current mesh rotation
  47753. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  47754. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  47755. this._cam_axisZ.normalize();
  47756. // same for camera up vector extracted from the cam view matrix
  47757. var view = this._camera.getViewMatrix(true);
  47758. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  47759. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  47760. this._cam_axisY.normalize();
  47761. this._cam_axisX.normalize();
  47762. }
  47763. // if depthSort, compute the camera global position in the mesh local system
  47764. if (this._depthSort) {
  47765. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  47766. }
  47767. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  47768. var idx = 0; // current position index in the global array positions32
  47769. var index = 0; // position start index in the global array positions32 of the current particle
  47770. var colidx = 0; // current color index in the global array colors32
  47771. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  47772. var uvidx = 0; // current uv index in the global array uvs32
  47773. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  47774. var pt = 0; // current index in the particle model shape
  47775. if (this.mesh.isFacetDataEnabled) {
  47776. this._computeBoundingBox = true;
  47777. }
  47778. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  47779. if (this._computeBoundingBox) {
  47780. if (start == 0 && end == this.nbParticles - 1) {
  47781. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  47782. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  47783. }
  47784. else {
  47785. if (this.mesh._boundingInfo) {
  47786. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  47787. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  47788. }
  47789. }
  47790. }
  47791. // particle loop
  47792. index = this.particles[start]._pos;
  47793. var vpos = (index / 3) | 0;
  47794. colorIndex = vpos * 4;
  47795. uvIndex = vpos * 2;
  47796. for (var p = start; p <= end; p++) {
  47797. this._particle = this.particles[p];
  47798. this._shape = this._particle._model._shape;
  47799. this._shapeUV = this._particle._model._shapeUV;
  47800. // call to custom user function to update the particle properties
  47801. this.updateParticle(this._particle);
  47802. // camera-particle distance for depth sorting
  47803. if (this._depthSort && this._depthSortParticles) {
  47804. var dsp = this.depthSortedParticles[p];
  47805. dsp.ind = this._particle._ind;
  47806. dsp.indicesLength = this._particle._model._indicesLength;
  47807. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  47808. }
  47809. // skip the computations for inactive or already invisible particles
  47810. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  47811. // increment indexes for the next particle
  47812. pt = this._shape.length;
  47813. index += pt * 3;
  47814. colorIndex += pt * 4;
  47815. uvIndex += pt * 2;
  47816. continue;
  47817. }
  47818. if (this._particle.isVisible) {
  47819. this._particle._stillInvisible = false; // un-mark permanent invisibility
  47820. // particle rotation matrix
  47821. if (this.billboard) {
  47822. this._particle.rotation.x = 0.0;
  47823. this._particle.rotation.y = 0.0;
  47824. }
  47825. if (this._computeParticleRotation || this.billboard) {
  47826. if (this._particle.rotationQuaternion) {
  47827. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47828. }
  47829. else {
  47830. this._yaw = this._particle.rotation.y;
  47831. this._pitch = this._particle.rotation.x;
  47832. this._roll = this._particle.rotation.z;
  47833. this._quaternionRotationYPR();
  47834. }
  47835. this._quaternionToRotationMatrix();
  47836. }
  47837. // particle vertex loop
  47838. for (pt = 0; pt < this._shape.length; pt++) {
  47839. idx = index + pt * 3;
  47840. colidx = colorIndex + pt * 4;
  47841. uvidx = uvIndex + pt * 2;
  47842. this._vertex.x = this._shape[pt].x;
  47843. this._vertex.y = this._shape[pt].y;
  47844. this._vertex.z = this._shape[pt].z;
  47845. if (this._computeParticleVertex) {
  47846. this.updateParticleVertex(this._particle, this._vertex, pt);
  47847. }
  47848. // positions
  47849. this._vertex.x *= this._particle.scaling.x;
  47850. this._vertex.y *= this._particle.scaling.y;
  47851. this._vertex.z *= this._particle.scaling.z;
  47852. this._vertex.x += this._particle.pivot.x;
  47853. this._vertex.y += this._particle.pivot.y;
  47854. this._vertex.z += this._particle.pivot.z;
  47855. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47856. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47857. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47858. 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;
  47859. 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;
  47860. 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;
  47861. if (this._computeBoundingBox) {
  47862. if (this._positions32[idx] < this._minimum.x) {
  47863. this._minimum.x = this._positions32[idx];
  47864. }
  47865. if (this._positions32[idx] > this._maximum.x) {
  47866. this._maximum.x = this._positions32[idx];
  47867. }
  47868. if (this._positions32[idx + 1] < this._minimum.y) {
  47869. this._minimum.y = this._positions32[idx + 1];
  47870. }
  47871. if (this._positions32[idx + 1] > this._maximum.y) {
  47872. this._maximum.y = this._positions32[idx + 1];
  47873. }
  47874. if (this._positions32[idx + 2] < this._minimum.z) {
  47875. this._minimum.z = this._positions32[idx + 2];
  47876. }
  47877. if (this._positions32[idx + 2] > this._maximum.z) {
  47878. this._maximum.z = this._positions32[idx + 2];
  47879. }
  47880. }
  47881. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  47882. if (!this._computeParticleVertex) {
  47883. this._normal.x = this._fixedNormal32[idx];
  47884. this._normal.y = this._fixedNormal32[idx + 1];
  47885. this._normal.z = this._fixedNormal32[idx + 2];
  47886. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  47887. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  47888. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  47889. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  47890. 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;
  47891. 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;
  47892. }
  47893. if (this._computeParticleColor && this._particle.color) {
  47894. this._colors32[colidx] = this._particle.color.r;
  47895. this._colors32[colidx + 1] = this._particle.color.g;
  47896. this._colors32[colidx + 2] = this._particle.color.b;
  47897. this._colors32[colidx + 3] = this._particle.color.a;
  47898. }
  47899. if (this._computeParticleTexture) {
  47900. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47901. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47902. }
  47903. }
  47904. }
  47905. else {
  47906. this._particle._stillInvisible = true; // mark the particle as invisible
  47907. for (pt = 0; pt < this._shape.length; pt++) {
  47908. idx = index + pt * 3;
  47909. colidx = colorIndex + pt * 4;
  47910. uvidx = uvIndex + pt * 2;
  47911. this._positions32[idx] = 0.0;
  47912. this._positions32[idx + 1] = 0.0;
  47913. this._positions32[idx + 2] = 0.0;
  47914. this._normals32[idx] = 0.0;
  47915. this._normals32[idx + 1] = 0.0;
  47916. this._normals32[idx + 2] = 0.0;
  47917. if (this._computeParticleColor && this._particle.color) {
  47918. this._colors32[colidx] = this._particle.color.r;
  47919. this._colors32[colidx + 1] = this._particle.color.g;
  47920. this._colors32[colidx + 2] = this._particle.color.b;
  47921. this._colors32[colidx + 3] = this._particle.color.a;
  47922. }
  47923. if (this._computeParticleTexture) {
  47924. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47925. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47926. }
  47927. }
  47928. }
  47929. // if the particle intersections must be computed : update the bbInfo
  47930. if (this._particlesIntersect) {
  47931. var bInfo = this._particle._boundingInfo;
  47932. var bBox = bInfo.boundingBox;
  47933. var bSphere = bInfo.boundingSphere;
  47934. if (!this._bSphereOnly) {
  47935. // place, scale and rotate the particle bbox within the SPS local system, then update it
  47936. for (var b = 0; b < bBox.vectors.length; b++) {
  47937. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  47938. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  47939. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  47940. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47941. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47942. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47943. 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;
  47944. 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;
  47945. 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;
  47946. }
  47947. bBox._update(this.mesh._worldMatrix);
  47948. }
  47949. // place and scale the particle bouding sphere in the SPS local system, then update it
  47950. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  47951. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  47952. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  47953. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  47954. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  47955. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  47956. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  47957. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  47958. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  47959. 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));
  47960. bSphere._update(this.mesh._worldMatrix);
  47961. }
  47962. // increment indexes for the next particle
  47963. index = idx + 3;
  47964. colorIndex = colidx + 4;
  47965. uvIndex = uvidx + 2;
  47966. }
  47967. // if the VBO must be updated
  47968. if (update) {
  47969. if (this._computeParticleColor) {
  47970. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  47971. }
  47972. if (this._computeParticleTexture) {
  47973. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  47974. }
  47975. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47976. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  47977. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  47978. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  47979. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  47980. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  47981. for (var i = 0; i < this._normals32.length; i++) {
  47982. this._fixedNormal32[i] = this._normals32[i];
  47983. }
  47984. }
  47985. if (!this.mesh.areNormalsFrozen) {
  47986. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  47987. }
  47988. }
  47989. if (this._depthSort && this._depthSortParticles) {
  47990. this.depthSortedParticles.sort(this._depthSortFunction);
  47991. var dspl = this.depthSortedParticles.length;
  47992. var sorted = 0;
  47993. var lind = 0;
  47994. var sind = 0;
  47995. var sid = 0;
  47996. for (sorted = 0; sorted < dspl; sorted++) {
  47997. lind = this.depthSortedParticles[sorted].indicesLength;
  47998. sind = this.depthSortedParticles[sorted].ind;
  47999. for (var i = 0; i < lind; i++) {
  48000. this._indices32[sid] = this._indices[sind + i];
  48001. sid++;
  48002. }
  48003. }
  48004. this.mesh.updateIndices(this._indices32);
  48005. }
  48006. }
  48007. if (this._computeBoundingBox) {
  48008. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  48009. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  48010. }
  48011. this.afterUpdateParticles(start, end, update);
  48012. return this;
  48013. };
  48014. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  48015. this._halfroll = this._roll * 0.5;
  48016. this._halfpitch = this._pitch * 0.5;
  48017. this._halfyaw = this._yaw * 0.5;
  48018. this._sinRoll = Math.sin(this._halfroll);
  48019. this._cosRoll = Math.cos(this._halfroll);
  48020. this._sinPitch = Math.sin(this._halfpitch);
  48021. this._cosPitch = Math.cos(this._halfpitch);
  48022. this._sinYaw = Math.sin(this._halfyaw);
  48023. this._cosYaw = Math.cos(this._halfyaw);
  48024. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  48025. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  48026. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  48027. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  48028. };
  48029. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  48030. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  48031. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  48032. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  48033. this._rotMatrix.m[3] = 0;
  48034. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  48035. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  48036. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  48037. this._rotMatrix.m[7] = 0;
  48038. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  48039. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  48040. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  48041. this._rotMatrix.m[11] = 0;
  48042. this._rotMatrix.m[12] = 0;
  48043. this._rotMatrix.m[13] = 0;
  48044. this._rotMatrix.m[14] = 0;
  48045. this._rotMatrix.m[15] = 1.0;
  48046. };
  48047. /**
  48048. * Disposes the SPS.
  48049. * Returns nothing.
  48050. */
  48051. SolidParticleSystem.prototype.dispose = function () {
  48052. this.mesh.dispose();
  48053. this.vars = null;
  48054. // drop references to internal big arrays for the GC
  48055. this._positions = null;
  48056. this._indices = null;
  48057. this._normals = null;
  48058. this._uvs = null;
  48059. this._colors = null;
  48060. this._indices32 = null;
  48061. this._positions32 = null;
  48062. this._normals32 = null;
  48063. this._fixedNormal32 = null;
  48064. this._uvs32 = null;
  48065. this._colors32 = null;
  48066. this.pickedParticles = null;
  48067. };
  48068. /**
  48069. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  48070. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48071. * Returns the SPS.
  48072. */
  48073. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  48074. if (!this._isVisibilityBoxLocked) {
  48075. this.mesh.refreshBoundingInfo();
  48076. }
  48077. return this;
  48078. };
  48079. /**
  48080. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  48081. * @param size the size (float) of the visibility box
  48082. * note : this doesn't lock the SPS mesh bounding box.
  48083. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48084. */
  48085. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  48086. var vis = size / 2;
  48087. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  48088. };
  48089. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  48090. // getter and setter
  48091. get: function () {
  48092. return this._alwaysVisible;
  48093. },
  48094. /**
  48095. * Sets the SPS as always visible or not
  48096. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48097. */
  48098. set: function (val) {
  48099. this._alwaysVisible = val;
  48100. this.mesh.alwaysSelectAsActiveMesh = val;
  48101. },
  48102. enumerable: true,
  48103. configurable: true
  48104. });
  48105. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  48106. get: function () {
  48107. return this._isVisibilityBoxLocked;
  48108. },
  48109. /**
  48110. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  48111. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48112. */
  48113. set: function (val) {
  48114. this._isVisibilityBoxLocked = val;
  48115. var boundingInfo = this.mesh.getBoundingInfo();
  48116. boundingInfo.isLocked = val;
  48117. },
  48118. enumerable: true,
  48119. configurable: true
  48120. });
  48121. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  48122. // getters
  48123. get: function () {
  48124. return this._computeParticleRotation;
  48125. },
  48126. // Optimizer setters
  48127. /**
  48128. * Tells to `setParticles()` to compute the particle rotations or not.
  48129. * Default value : true. The SPS is faster when it's set to false.
  48130. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  48131. */
  48132. set: function (val) {
  48133. this._computeParticleRotation = val;
  48134. },
  48135. enumerable: true,
  48136. configurable: true
  48137. });
  48138. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  48139. get: function () {
  48140. return this._computeParticleColor;
  48141. },
  48142. /**
  48143. * Tells to `setParticles()` to compute the particle colors or not.
  48144. * Default value : true. The SPS is faster when it's set to false.
  48145. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  48146. */
  48147. set: function (val) {
  48148. this._computeParticleColor = val;
  48149. },
  48150. enumerable: true,
  48151. configurable: true
  48152. });
  48153. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  48154. get: function () {
  48155. return this._computeParticleTexture;
  48156. },
  48157. /**
  48158. * Tells to `setParticles()` to compute the particle textures or not.
  48159. * Default value : true. The SPS is faster when it's set to false.
  48160. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  48161. */
  48162. set: function (val) {
  48163. this._computeParticleTexture = val;
  48164. },
  48165. enumerable: true,
  48166. configurable: true
  48167. });
  48168. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  48169. get: function () {
  48170. return this._computeParticleVertex;
  48171. },
  48172. /**
  48173. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  48174. * Default value : false. The SPS is faster when it's set to false.
  48175. * Note : the particle custom vertex positions aren't stored values.
  48176. */
  48177. set: function (val) {
  48178. this._computeParticleVertex = val;
  48179. },
  48180. enumerable: true,
  48181. configurable: true
  48182. });
  48183. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  48184. get: function () {
  48185. return this._computeBoundingBox;
  48186. },
  48187. /**
  48188. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  48189. */
  48190. set: function (val) {
  48191. this._computeBoundingBox = val;
  48192. },
  48193. enumerable: true,
  48194. configurable: true
  48195. });
  48196. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  48197. get: function () {
  48198. return this._depthSortParticles;
  48199. },
  48200. /**
  48201. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  48202. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  48203. * Default : `true`
  48204. */
  48205. set: function (val) {
  48206. this._depthSortParticles = val;
  48207. },
  48208. enumerable: true,
  48209. configurable: true
  48210. });
  48211. // =======================================================================
  48212. // Particle behavior logic
  48213. // these following methods may be overwritten by the user to fit his needs
  48214. /**
  48215. * This function does nothing. It may be overwritten to set all the particle first values.
  48216. * The SPS doesn't call this function, you may have to call it by your own.
  48217. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48218. */
  48219. SolidParticleSystem.prototype.initParticles = function () {
  48220. };
  48221. /**
  48222. * This function does nothing. It may be overwritten to recycle a particle.
  48223. * The SPS doesn't call this function, you may have to call it by your own.
  48224. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48225. */
  48226. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  48227. return particle;
  48228. };
  48229. /**
  48230. * Updates a particle : this function should be overwritten by the user.
  48231. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  48232. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48233. * ex : just set a particle position or velocity and recycle conditions
  48234. */
  48235. SolidParticleSystem.prototype.updateParticle = function (particle) {
  48236. return particle;
  48237. };
  48238. /**
  48239. * Updates a vertex of a particle : it can be overwritten by the user.
  48240. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  48241. * @param particle the current particle
  48242. * @param vertex the current index of the current particle
  48243. * @param pt the index of the current vertex in the particle shape
  48244. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  48245. * ex : just set a vertex particle position
  48246. */
  48247. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  48248. return vertex;
  48249. };
  48250. /**
  48251. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  48252. * This does nothing and may be overwritten by the user.
  48253. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48254. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48255. * @param update the boolean update value actually passed to setParticles()
  48256. */
  48257. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  48258. };
  48259. /**
  48260. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  48261. * This will be passed three parameters.
  48262. * This does nothing and may be overwritten by the user.
  48263. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48264. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48265. * @param update the boolean update value actually passed to setParticles()
  48266. */
  48267. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  48268. };
  48269. return SolidParticleSystem;
  48270. }());
  48271. BABYLON.SolidParticleSystem = SolidParticleSystem;
  48272. })(BABYLON || (BABYLON = {}));
  48273. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  48274. var BABYLON;
  48275. (function (BABYLON) {
  48276. var ShaderMaterial = /** @class */ (function (_super) {
  48277. __extends(ShaderMaterial, _super);
  48278. function ShaderMaterial(name, scene, shaderPath, options) {
  48279. var _this = _super.call(this, name, scene) || this;
  48280. _this._textures = {};
  48281. _this._textureArrays = {};
  48282. _this._floats = {};
  48283. _this._ints = {};
  48284. _this._floatsArrays = {};
  48285. _this._colors3 = {};
  48286. _this._colors3Arrays = {};
  48287. _this._colors4 = {};
  48288. _this._vectors2 = {};
  48289. _this._vectors3 = {};
  48290. _this._vectors4 = {};
  48291. _this._matrices = {};
  48292. _this._matrices3x3 = {};
  48293. _this._matrices2x2 = {};
  48294. _this._vectors2Arrays = {};
  48295. _this._vectors3Arrays = {};
  48296. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  48297. _this._shaderPath = shaderPath;
  48298. options.needAlphaBlending = options.needAlphaBlending || false;
  48299. options.needAlphaTesting = options.needAlphaTesting || false;
  48300. options.attributes = options.attributes || ["position", "normal", "uv"];
  48301. options.uniforms = options.uniforms || ["worldViewProjection"];
  48302. options.uniformBuffers = options.uniformBuffers || [];
  48303. options.samplers = options.samplers || [];
  48304. options.defines = options.defines || [];
  48305. _this._options = options;
  48306. return _this;
  48307. }
  48308. ShaderMaterial.prototype.getClassName = function () {
  48309. return "ShaderMaterial";
  48310. };
  48311. ShaderMaterial.prototype.needAlphaBlending = function () {
  48312. return this._options.needAlphaBlending;
  48313. };
  48314. ShaderMaterial.prototype.needAlphaTesting = function () {
  48315. return this._options.needAlphaTesting;
  48316. };
  48317. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  48318. if (this._options.uniforms.indexOf(uniformName) === -1) {
  48319. this._options.uniforms.push(uniformName);
  48320. }
  48321. };
  48322. ShaderMaterial.prototype.setTexture = function (name, texture) {
  48323. if (this._options.samplers.indexOf(name) === -1) {
  48324. this._options.samplers.push(name);
  48325. }
  48326. this._textures[name] = texture;
  48327. return this;
  48328. };
  48329. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  48330. if (this._options.samplers.indexOf(name) === -1) {
  48331. this._options.samplers.push(name);
  48332. }
  48333. this._checkUniform(name);
  48334. this._textureArrays[name] = textures;
  48335. return this;
  48336. };
  48337. ShaderMaterial.prototype.setFloat = function (name, value) {
  48338. this._checkUniform(name);
  48339. this._floats[name] = value;
  48340. return this;
  48341. };
  48342. ShaderMaterial.prototype.setInt = function (name, value) {
  48343. this._checkUniform(name);
  48344. this._ints[name] = value;
  48345. return this;
  48346. };
  48347. ShaderMaterial.prototype.setFloats = function (name, value) {
  48348. this._checkUniform(name);
  48349. this._floatsArrays[name] = value;
  48350. return this;
  48351. };
  48352. ShaderMaterial.prototype.setColor3 = function (name, value) {
  48353. this._checkUniform(name);
  48354. this._colors3[name] = value;
  48355. return this;
  48356. };
  48357. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  48358. this._checkUniform(name);
  48359. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  48360. color.toArray(arr, arr.length);
  48361. return arr;
  48362. }, []);
  48363. return this;
  48364. };
  48365. ShaderMaterial.prototype.setColor4 = function (name, value) {
  48366. this._checkUniform(name);
  48367. this._colors4[name] = value;
  48368. return this;
  48369. };
  48370. ShaderMaterial.prototype.setVector2 = function (name, value) {
  48371. this._checkUniform(name);
  48372. this._vectors2[name] = value;
  48373. return this;
  48374. };
  48375. ShaderMaterial.prototype.setVector3 = function (name, value) {
  48376. this._checkUniform(name);
  48377. this._vectors3[name] = value;
  48378. return this;
  48379. };
  48380. ShaderMaterial.prototype.setVector4 = function (name, value) {
  48381. this._checkUniform(name);
  48382. this._vectors4[name] = value;
  48383. return this;
  48384. };
  48385. ShaderMaterial.prototype.setMatrix = function (name, value) {
  48386. this._checkUniform(name);
  48387. this._matrices[name] = value;
  48388. return this;
  48389. };
  48390. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  48391. this._checkUniform(name);
  48392. this._matrices3x3[name] = value;
  48393. return this;
  48394. };
  48395. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  48396. this._checkUniform(name);
  48397. this._matrices2x2[name] = value;
  48398. return this;
  48399. };
  48400. ShaderMaterial.prototype.setArray2 = function (name, value) {
  48401. this._checkUniform(name);
  48402. this._vectors2Arrays[name] = value;
  48403. return this;
  48404. };
  48405. ShaderMaterial.prototype.setArray3 = function (name, value) {
  48406. this._checkUniform(name);
  48407. this._vectors3Arrays[name] = value;
  48408. return this;
  48409. };
  48410. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  48411. if (!mesh) {
  48412. return true;
  48413. }
  48414. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  48415. return false;
  48416. }
  48417. return false;
  48418. };
  48419. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  48420. var scene = this.getScene();
  48421. var engine = scene.getEngine();
  48422. if (!this.checkReadyOnEveryCall) {
  48423. if (this._renderId === scene.getRenderId()) {
  48424. if (this._checkCache(scene, mesh, useInstances)) {
  48425. return true;
  48426. }
  48427. }
  48428. }
  48429. // Instances
  48430. var defines = [];
  48431. var attribs = [];
  48432. var fallbacks = new BABYLON.EffectFallbacks();
  48433. if (useInstances) {
  48434. defines.push("#define INSTANCES");
  48435. }
  48436. for (var index = 0; index < this._options.defines.length; index++) {
  48437. defines.push(this._options.defines[index]);
  48438. }
  48439. for (var index = 0; index < this._options.attributes.length; index++) {
  48440. attribs.push(this._options.attributes[index]);
  48441. }
  48442. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  48443. attribs.push(BABYLON.VertexBuffer.ColorKind);
  48444. defines.push("#define VERTEXCOLOR");
  48445. }
  48446. // Bones
  48447. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  48448. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48449. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48450. if (mesh.numBoneInfluencers > 4) {
  48451. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48452. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48453. }
  48454. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48455. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48456. fallbacks.addCPUSkinningFallback(0, mesh);
  48457. if (this._options.uniforms.indexOf("mBones") === -1) {
  48458. this._options.uniforms.push("mBones");
  48459. }
  48460. }
  48461. else {
  48462. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48463. }
  48464. // Textures
  48465. for (var name in this._textures) {
  48466. if (!this._textures[name].isReady()) {
  48467. return false;
  48468. }
  48469. }
  48470. // Alpha test
  48471. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  48472. defines.push("#define ALPHATEST");
  48473. }
  48474. var previousEffect = this._effect;
  48475. var join = defines.join("\n");
  48476. this._effect = engine.createEffect(this._shaderPath, {
  48477. attributes: attribs,
  48478. uniformsNames: this._options.uniforms,
  48479. uniformBuffersNames: this._options.uniformBuffers,
  48480. samplers: this._options.samplers,
  48481. defines: join,
  48482. fallbacks: fallbacks,
  48483. onCompiled: this.onCompiled,
  48484. onError: this.onError
  48485. }, engine);
  48486. if (!this._effect.isReady()) {
  48487. return false;
  48488. }
  48489. if (previousEffect !== this._effect) {
  48490. scene.resetCachedMaterial();
  48491. }
  48492. this._renderId = scene.getRenderId();
  48493. return true;
  48494. };
  48495. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  48496. var scene = this.getScene();
  48497. if (!this._effect) {
  48498. return;
  48499. }
  48500. if (this._options.uniforms.indexOf("world") !== -1) {
  48501. this._effect.setMatrix("world", world);
  48502. }
  48503. if (this._options.uniforms.indexOf("worldView") !== -1) {
  48504. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  48505. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  48506. }
  48507. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  48508. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  48509. }
  48510. };
  48511. ShaderMaterial.prototype.bind = function (world, mesh) {
  48512. // Std values
  48513. this.bindOnlyWorldMatrix(world);
  48514. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  48515. if (this._options.uniforms.indexOf("view") !== -1) {
  48516. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  48517. }
  48518. if (this._options.uniforms.indexOf("projection") !== -1) {
  48519. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  48520. }
  48521. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  48522. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  48523. }
  48524. // Bones
  48525. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  48526. var name;
  48527. // Texture
  48528. for (name in this._textures) {
  48529. this._effect.setTexture(name, this._textures[name]);
  48530. }
  48531. // Texture arrays
  48532. for (name in this._textureArrays) {
  48533. this._effect.setTextureArray(name, this._textureArrays[name]);
  48534. }
  48535. // Int
  48536. for (name in this._ints) {
  48537. this._effect.setInt(name, this._ints[name]);
  48538. }
  48539. // Float
  48540. for (name in this._floats) {
  48541. this._effect.setFloat(name, this._floats[name]);
  48542. }
  48543. // Floats
  48544. for (name in this._floatsArrays) {
  48545. this._effect.setArray(name, this._floatsArrays[name]);
  48546. }
  48547. // Color3
  48548. for (name in this._colors3) {
  48549. this._effect.setColor3(name, this._colors3[name]);
  48550. }
  48551. for (name in this._colors3Arrays) {
  48552. this._effect.setArray3(name, this._colors3Arrays[name]);
  48553. }
  48554. // Color4
  48555. for (name in this._colors4) {
  48556. var color = this._colors4[name];
  48557. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  48558. }
  48559. // Vector2
  48560. for (name in this._vectors2) {
  48561. this._effect.setVector2(name, this._vectors2[name]);
  48562. }
  48563. // Vector3
  48564. for (name in this._vectors3) {
  48565. this._effect.setVector3(name, this._vectors3[name]);
  48566. }
  48567. // Vector4
  48568. for (name in this._vectors4) {
  48569. this._effect.setVector4(name, this._vectors4[name]);
  48570. }
  48571. // Matrix
  48572. for (name in this._matrices) {
  48573. this._effect.setMatrix(name, this._matrices[name]);
  48574. }
  48575. // Matrix 3x3
  48576. for (name in this._matrices3x3) {
  48577. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  48578. }
  48579. // Matrix 2x2
  48580. for (name in this._matrices2x2) {
  48581. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  48582. }
  48583. // Vector2Array
  48584. for (name in this._vectors2Arrays) {
  48585. this._effect.setArray2(name, this._vectors2Arrays[name]);
  48586. }
  48587. // Vector3Array
  48588. for (name in this._vectors3Arrays) {
  48589. this._effect.setArray3(name, this._vectors3Arrays[name]);
  48590. }
  48591. }
  48592. this._afterBind(mesh);
  48593. };
  48594. ShaderMaterial.prototype.getActiveTextures = function () {
  48595. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48596. for (var name in this._textures) {
  48597. activeTextures.push(this._textures[name]);
  48598. }
  48599. for (var name in this._textureArrays) {
  48600. var array = this._textureArrays[name];
  48601. for (var index = 0; index < array.length; index++) {
  48602. activeTextures.push(array[index]);
  48603. }
  48604. }
  48605. return activeTextures;
  48606. };
  48607. ShaderMaterial.prototype.hasTexture = function (texture) {
  48608. if (_super.prototype.hasTexture.call(this, texture)) {
  48609. return true;
  48610. }
  48611. for (var name in this._textures) {
  48612. if (this._textures[name] === texture) {
  48613. return true;
  48614. }
  48615. }
  48616. for (var name in this._textureArrays) {
  48617. var array = this._textureArrays[name];
  48618. for (var index = 0; index < array.length; index++) {
  48619. if (array[index] === texture) {
  48620. return true;
  48621. }
  48622. }
  48623. }
  48624. return false;
  48625. };
  48626. ShaderMaterial.prototype.clone = function (name) {
  48627. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  48628. return newShaderMaterial;
  48629. };
  48630. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48631. if (forceDisposeTextures) {
  48632. var name;
  48633. for (name in this._textures) {
  48634. this._textures[name].dispose();
  48635. }
  48636. for (name in this._textureArrays) {
  48637. var array = this._textureArrays[name];
  48638. for (var index = 0; index < array.length; index++) {
  48639. array[index].dispose();
  48640. }
  48641. }
  48642. }
  48643. this._textures = {};
  48644. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48645. };
  48646. ShaderMaterial.prototype.serialize = function () {
  48647. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48648. serializationObject.customType = "BABYLON.ShaderMaterial";
  48649. serializationObject.options = this._options;
  48650. serializationObject.shaderPath = this._shaderPath;
  48651. var name;
  48652. // Texture
  48653. serializationObject.textures = {};
  48654. for (name in this._textures) {
  48655. serializationObject.textures[name] = this._textures[name].serialize();
  48656. }
  48657. // Texture arrays
  48658. serializationObject.textureArrays = {};
  48659. for (name in this._textureArrays) {
  48660. serializationObject.textureArrays[name] = [];
  48661. var array = this._textureArrays[name];
  48662. for (var index = 0; index < array.length; index++) {
  48663. serializationObject.textureArrays[name].push(array[index].serialize());
  48664. }
  48665. }
  48666. // Float
  48667. serializationObject.floats = {};
  48668. for (name in this._floats) {
  48669. serializationObject.floats[name] = this._floats[name];
  48670. }
  48671. // Float s
  48672. serializationObject.FloatArrays = {};
  48673. for (name in this._floatsArrays) {
  48674. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  48675. }
  48676. // Color3
  48677. serializationObject.colors3 = {};
  48678. for (name in this._colors3) {
  48679. serializationObject.colors3[name] = this._colors3[name].asArray();
  48680. }
  48681. // Color3 array
  48682. serializationObject.colors3Arrays = {};
  48683. for (name in this._colors3Arrays) {
  48684. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  48685. }
  48686. // Color4
  48687. serializationObject.colors4 = {};
  48688. for (name in this._colors4) {
  48689. serializationObject.colors4[name] = this._colors4[name].asArray();
  48690. }
  48691. // Vector2
  48692. serializationObject.vectors2 = {};
  48693. for (name in this._vectors2) {
  48694. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  48695. }
  48696. // Vector3
  48697. serializationObject.vectors3 = {};
  48698. for (name in this._vectors3) {
  48699. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  48700. }
  48701. // Vector4
  48702. serializationObject.vectors4 = {};
  48703. for (name in this._vectors4) {
  48704. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  48705. }
  48706. // Matrix
  48707. serializationObject.matrices = {};
  48708. for (name in this._matrices) {
  48709. serializationObject.matrices[name] = this._matrices[name].asArray();
  48710. }
  48711. // Matrix 3x3
  48712. serializationObject.matrices3x3 = {};
  48713. for (name in this._matrices3x3) {
  48714. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  48715. }
  48716. // Matrix 2x2
  48717. serializationObject.matrices2x2 = {};
  48718. for (name in this._matrices2x2) {
  48719. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  48720. }
  48721. // Vector2Array
  48722. serializationObject.vectors2Arrays = {};
  48723. for (name in this._vectors2Arrays) {
  48724. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  48725. }
  48726. // Vector3Array
  48727. serializationObject.vectors3Arrays = {};
  48728. for (name in this._vectors3Arrays) {
  48729. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  48730. }
  48731. return serializationObject;
  48732. };
  48733. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  48734. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  48735. var name;
  48736. // Texture
  48737. for (name in source.textures) {
  48738. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  48739. }
  48740. // Texture arrays
  48741. for (name in source.textureArrays) {
  48742. var array = source.textureArrays[name];
  48743. var textureArray = new Array();
  48744. for (var index = 0; index < array.length; index++) {
  48745. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  48746. }
  48747. material.setTextureArray(name, textureArray);
  48748. }
  48749. // Float
  48750. for (name in source.floats) {
  48751. material.setFloat(name, source.floats[name]);
  48752. }
  48753. // Float s
  48754. for (name in source.floatsArrays) {
  48755. material.setFloats(name, source.floatsArrays[name]);
  48756. }
  48757. // Color3
  48758. for (name in source.colors3) {
  48759. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  48760. }
  48761. // Color3 arrays
  48762. for (name in source.colors3Arrays) {
  48763. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  48764. if (i % 3 === 0) {
  48765. arr.push([num]);
  48766. }
  48767. else {
  48768. arr[arr.length - 1].push(num);
  48769. }
  48770. return arr;
  48771. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  48772. material.setColor3Array(name, colors);
  48773. }
  48774. // Color4
  48775. for (name in source.colors4) {
  48776. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  48777. }
  48778. // Vector2
  48779. for (name in source.vectors2) {
  48780. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  48781. }
  48782. // Vector3
  48783. for (name in source.vectors3) {
  48784. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  48785. }
  48786. // Vector4
  48787. for (name in source.vectors4) {
  48788. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  48789. }
  48790. // Matrix
  48791. for (name in source.matrices) {
  48792. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  48793. }
  48794. // Matrix 3x3
  48795. for (name in source.matrices3x3) {
  48796. material.setMatrix3x3(name, source.matrices3x3[name]);
  48797. }
  48798. // Matrix 2x2
  48799. for (name in source.matrices2x2) {
  48800. material.setMatrix2x2(name, source.matrices2x2[name]);
  48801. }
  48802. // Vector2Array
  48803. for (name in source.vectors2Arrays) {
  48804. material.setArray2(name, source.vectors2Arrays[name]);
  48805. }
  48806. // Vector3Array
  48807. for (name in source.vectors3Arrays) {
  48808. material.setArray3(name, source.vectors3Arrays[name]);
  48809. }
  48810. return material;
  48811. };
  48812. return ShaderMaterial;
  48813. }(BABYLON.Material));
  48814. BABYLON.ShaderMaterial = ShaderMaterial;
  48815. })(BABYLON || (BABYLON = {}));
  48816. //# sourceMappingURL=babylon.shaderMaterial.js.map
  48817. var BABYLON;
  48818. (function (BABYLON) {
  48819. var GroundMesh = /** @class */ (function (_super) {
  48820. __extends(GroundMesh, _super);
  48821. function GroundMesh(name, scene) {
  48822. var _this = _super.call(this, name, scene) || this;
  48823. _this.generateOctree = false;
  48824. return _this;
  48825. }
  48826. GroundMesh.prototype.getClassName = function () {
  48827. return "GroundMesh";
  48828. };
  48829. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  48830. get: function () {
  48831. return Math.min(this._subdivisionsX, this._subdivisionsY);
  48832. },
  48833. enumerable: true,
  48834. configurable: true
  48835. });
  48836. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  48837. get: function () {
  48838. return this._subdivisionsX;
  48839. },
  48840. enumerable: true,
  48841. configurable: true
  48842. });
  48843. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  48844. get: function () {
  48845. return this._subdivisionsY;
  48846. },
  48847. enumerable: true,
  48848. configurable: true
  48849. });
  48850. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  48851. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  48852. this._subdivisionsX = chunksCount;
  48853. this._subdivisionsY = chunksCount;
  48854. this.subdivide(chunksCount);
  48855. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  48856. };
  48857. /**
  48858. * Returns a height (y) value in the Worl system :
  48859. * the ground altitude at the coordinates (x, z) expressed in the World system.
  48860. * Returns the ground y position if (x, z) are outside the ground surface.
  48861. */
  48862. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  48863. var world = this.getWorldMatrix();
  48864. var invMat = BABYLON.Tmp.Matrix[5];
  48865. world.invertToRef(invMat);
  48866. var tmpVect = BABYLON.Tmp.Vector3[8];
  48867. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  48868. x = tmpVect.x;
  48869. z = tmpVect.z;
  48870. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  48871. return this.position.y;
  48872. }
  48873. if (!this._heightQuads || this._heightQuads.length == 0) {
  48874. this._initHeightQuads();
  48875. this._computeHeightQuads();
  48876. }
  48877. var facet = this._getFacetAt(x, z);
  48878. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  48879. // return y in the World system
  48880. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  48881. return tmpVect.y;
  48882. };
  48883. /**
  48884. * Returns a normalized vector (Vector3) orthogonal to the ground
  48885. * at the ground coordinates (x, z) expressed in the World system.
  48886. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  48887. */
  48888. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  48889. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  48890. this.getNormalAtCoordinatesToRef(x, z, normal);
  48891. return normal;
  48892. };
  48893. /**
  48894. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  48895. * at the ground coordinates (x, z) expressed in the World system.
  48896. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  48897. * Returns the GroundMesh.
  48898. */
  48899. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  48900. var world = this.getWorldMatrix();
  48901. var tmpMat = BABYLON.Tmp.Matrix[5];
  48902. world.invertToRef(tmpMat);
  48903. var tmpVect = BABYLON.Tmp.Vector3[8];
  48904. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  48905. x = tmpVect.x;
  48906. z = tmpVect.z;
  48907. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  48908. return this;
  48909. }
  48910. if (!this._heightQuads || this._heightQuads.length == 0) {
  48911. this._initHeightQuads();
  48912. this._computeHeightQuads();
  48913. }
  48914. var facet = this._getFacetAt(x, z);
  48915. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  48916. return this;
  48917. };
  48918. /**
  48919. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  48920. * if the ground has been updated.
  48921. * This can be used in the render loop.
  48922. * Returns the GroundMesh.
  48923. */
  48924. GroundMesh.prototype.updateCoordinateHeights = function () {
  48925. if (!this._heightQuads || this._heightQuads.length == 0) {
  48926. this._initHeightQuads();
  48927. }
  48928. this._computeHeightQuads();
  48929. return this;
  48930. };
  48931. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  48932. GroundMesh.prototype._getFacetAt = function (x, z) {
  48933. // retrieve col and row from x, z coordinates in the ground local system
  48934. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  48935. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  48936. var quad = this._heightQuads[row * this._subdivisionsX + col];
  48937. var facet;
  48938. if (z < quad.slope.x * x + quad.slope.y) {
  48939. facet = quad.facet1;
  48940. }
  48941. else {
  48942. facet = quad.facet2;
  48943. }
  48944. return facet;
  48945. };
  48946. // Creates and populates the heightMap array with "facet" elements :
  48947. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  48948. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  48949. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  48950. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  48951. // Returns the GroundMesh.
  48952. GroundMesh.prototype._initHeightQuads = function () {
  48953. var subdivisionsX = this._subdivisionsX;
  48954. var subdivisionsY = this._subdivisionsY;
  48955. this._heightQuads = new Array();
  48956. for (var row = 0; row < subdivisionsY; row++) {
  48957. for (var col = 0; col < subdivisionsX; col++) {
  48958. 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) };
  48959. this._heightQuads[row * subdivisionsX + col] = quad;
  48960. }
  48961. }
  48962. return this;
  48963. };
  48964. // Compute each quad element values and update the the heightMap array :
  48965. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  48966. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  48967. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  48968. // Returns the GroundMesh.
  48969. GroundMesh.prototype._computeHeightQuads = function () {
  48970. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48971. if (!positions) {
  48972. return this;
  48973. }
  48974. var v1 = BABYLON.Tmp.Vector3[3];
  48975. var v2 = BABYLON.Tmp.Vector3[2];
  48976. var v3 = BABYLON.Tmp.Vector3[1];
  48977. var v4 = BABYLON.Tmp.Vector3[0];
  48978. var v1v2 = BABYLON.Tmp.Vector3[4];
  48979. var v1v3 = BABYLON.Tmp.Vector3[5];
  48980. var v1v4 = BABYLON.Tmp.Vector3[6];
  48981. var norm1 = BABYLON.Tmp.Vector3[7];
  48982. var norm2 = BABYLON.Tmp.Vector3[8];
  48983. var i = 0;
  48984. var j = 0;
  48985. var k = 0;
  48986. var cd = 0; // 2D slope coefficient : z = cd * x + h
  48987. var h = 0;
  48988. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  48989. var d2 = 0;
  48990. var subdivisionsX = this._subdivisionsX;
  48991. var subdivisionsY = this._subdivisionsY;
  48992. for (var row = 0; row < subdivisionsY; row++) {
  48993. for (var col = 0; col < subdivisionsX; col++) {
  48994. i = col * 3;
  48995. j = row * (subdivisionsX + 1) * 3;
  48996. k = (row + 1) * (subdivisionsX + 1) * 3;
  48997. v1.x = positions[j + i];
  48998. v1.y = positions[j + i + 1];
  48999. v1.z = positions[j + i + 2];
  49000. v2.x = positions[j + i + 3];
  49001. v2.y = positions[j + i + 4];
  49002. v2.z = positions[j + i + 5];
  49003. v3.x = positions[k + i];
  49004. v3.y = positions[k + i + 1];
  49005. v3.z = positions[k + i + 2];
  49006. v4.x = positions[k + i + 3];
  49007. v4.y = positions[k + i + 4];
  49008. v4.z = positions[k + i + 5];
  49009. // 2D slope V1V4
  49010. cd = (v4.z - v1.z) / (v4.x - v1.x);
  49011. h = v1.z - cd * v1.x; // v1 belongs to the slope
  49012. // facet equations :
  49013. // we compute each facet normal vector
  49014. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  49015. // we compute the value d by applying the equation to v1 which belongs to the plane
  49016. // then we store the facet equation in a Vector4
  49017. v2.subtractToRef(v1, v1v2);
  49018. v3.subtractToRef(v1, v1v3);
  49019. v4.subtractToRef(v1, v1v4);
  49020. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  49021. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  49022. norm1.normalize();
  49023. norm2.normalize();
  49024. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  49025. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  49026. var quad = this._heightQuads[row * subdivisionsX + col];
  49027. quad.slope.copyFromFloats(cd, h);
  49028. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  49029. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  49030. }
  49031. }
  49032. return this;
  49033. };
  49034. GroundMesh.prototype.serialize = function (serializationObject) {
  49035. _super.prototype.serialize.call(this, serializationObject);
  49036. serializationObject.subdivisionsX = this._subdivisionsX;
  49037. serializationObject.subdivisionsY = this._subdivisionsY;
  49038. serializationObject.minX = this._minX;
  49039. serializationObject.maxX = this._maxX;
  49040. serializationObject.minZ = this._minZ;
  49041. serializationObject.maxZ = this._maxZ;
  49042. serializationObject.width = this._width;
  49043. serializationObject.height = this._height;
  49044. };
  49045. GroundMesh.Parse = function (parsedMesh, scene) {
  49046. var result = new GroundMesh(parsedMesh.name, scene);
  49047. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  49048. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  49049. result._minX = parsedMesh.minX;
  49050. result._maxX = parsedMesh.maxX;
  49051. result._minZ = parsedMesh.minZ;
  49052. result._maxZ = parsedMesh.maxZ;
  49053. result._width = parsedMesh.width;
  49054. result._height = parsedMesh.height;
  49055. return result;
  49056. };
  49057. return GroundMesh;
  49058. }(BABYLON.Mesh));
  49059. BABYLON.GroundMesh = GroundMesh;
  49060. })(BABYLON || (BABYLON = {}));
  49061. //# sourceMappingURL=babylon.groundMesh.js.map
  49062. var BABYLON;
  49063. (function (BABYLON) {
  49064. /**
  49065. * Creates an instance based on a source mesh.
  49066. */
  49067. var InstancedMesh = /** @class */ (function (_super) {
  49068. __extends(InstancedMesh, _super);
  49069. function InstancedMesh(name, source) {
  49070. var _this = _super.call(this, name, source.getScene()) || this;
  49071. source.instances.push(_this);
  49072. _this._sourceMesh = source;
  49073. _this.position.copyFrom(source.position);
  49074. _this.rotation.copyFrom(source.rotation);
  49075. _this.scaling.copyFrom(source.scaling);
  49076. if (source.rotationQuaternion) {
  49077. _this.rotationQuaternion = source.rotationQuaternion.clone();
  49078. }
  49079. _this.infiniteDistance = source.infiniteDistance;
  49080. _this.setPivotMatrix(source.getPivotMatrix());
  49081. _this.refreshBoundingInfo();
  49082. _this._syncSubMeshes();
  49083. return _this;
  49084. }
  49085. /**
  49086. * Returns the string "InstancedMesh".
  49087. */
  49088. InstancedMesh.prototype.getClassName = function () {
  49089. return "InstancedMesh";
  49090. };
  49091. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  49092. // Methods
  49093. get: function () {
  49094. return this._sourceMesh.receiveShadows;
  49095. },
  49096. enumerable: true,
  49097. configurable: true
  49098. });
  49099. Object.defineProperty(InstancedMesh.prototype, "material", {
  49100. get: function () {
  49101. return this._sourceMesh.material;
  49102. },
  49103. enumerable: true,
  49104. configurable: true
  49105. });
  49106. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  49107. get: function () {
  49108. return this._sourceMesh.visibility;
  49109. },
  49110. enumerable: true,
  49111. configurable: true
  49112. });
  49113. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  49114. get: function () {
  49115. return this._sourceMesh.skeleton;
  49116. },
  49117. enumerable: true,
  49118. configurable: true
  49119. });
  49120. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  49121. get: function () {
  49122. return this._sourceMesh.renderingGroupId;
  49123. },
  49124. enumerable: true,
  49125. configurable: true
  49126. });
  49127. /**
  49128. * Returns the total number of vertices (integer).
  49129. */
  49130. InstancedMesh.prototype.getTotalVertices = function () {
  49131. return this._sourceMesh.getTotalVertices();
  49132. };
  49133. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  49134. get: function () {
  49135. return this._sourceMesh;
  49136. },
  49137. enumerable: true,
  49138. configurable: true
  49139. });
  49140. /**
  49141. * Is this node ready to be used/rendered
  49142. * @return {boolean} is it ready
  49143. */
  49144. InstancedMesh.prototype.isReady = function () {
  49145. return this._sourceMesh.isReady(true);
  49146. };
  49147. /**
  49148. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  49149. */
  49150. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  49151. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  49152. };
  49153. /**
  49154. * Sets the vertex data of the mesh geometry for the requested `kind`.
  49155. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  49156. * The `data` are either a numeric array either a Float32Array.
  49157. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  49158. * 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).
  49159. * Note that a new underlying VertexBuffer object is created each call.
  49160. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  49161. *
  49162. * Possible `kind` values :
  49163. * - BABYLON.VertexBuffer.PositionKind
  49164. * - BABYLON.VertexBuffer.UVKind
  49165. * - BABYLON.VertexBuffer.UV2Kind
  49166. * - BABYLON.VertexBuffer.UV3Kind
  49167. * - BABYLON.VertexBuffer.UV4Kind
  49168. * - BABYLON.VertexBuffer.UV5Kind
  49169. * - BABYLON.VertexBuffer.UV6Kind
  49170. * - BABYLON.VertexBuffer.ColorKind
  49171. * - BABYLON.VertexBuffer.MatricesIndicesKind
  49172. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  49173. * - BABYLON.VertexBuffer.MatricesWeightsKind
  49174. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  49175. *
  49176. * Returns the Mesh.
  49177. */
  49178. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  49179. if (this.sourceMesh) {
  49180. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  49181. }
  49182. return this.sourceMesh;
  49183. };
  49184. /**
  49185. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  49186. * If the mesh has no geometry, it is simply returned as it is.
  49187. * The `data` are either a numeric array either a Float32Array.
  49188. * No new underlying VertexBuffer object is created.
  49189. * 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.
  49190. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  49191. *
  49192. * Possible `kind` values :
  49193. * - BABYLON.VertexBuffer.PositionKind
  49194. * - BABYLON.VertexBuffer.UVKind
  49195. * - BABYLON.VertexBuffer.UV2Kind
  49196. * - BABYLON.VertexBuffer.UV3Kind
  49197. * - BABYLON.VertexBuffer.UV4Kind
  49198. * - BABYLON.VertexBuffer.UV5Kind
  49199. * - BABYLON.VertexBuffer.UV6Kind
  49200. * - BABYLON.VertexBuffer.ColorKind
  49201. * - BABYLON.VertexBuffer.MatricesIndicesKind
  49202. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  49203. * - BABYLON.VertexBuffer.MatricesWeightsKind
  49204. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  49205. *
  49206. * Returns the Mesh.
  49207. */
  49208. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  49209. if (this.sourceMesh) {
  49210. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  49211. }
  49212. return this.sourceMesh;
  49213. };
  49214. /**
  49215. * Sets the mesh indices.
  49216. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  49217. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  49218. * This method creates a new index buffer each call.
  49219. * Returns the Mesh.
  49220. */
  49221. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  49222. if (totalVertices === void 0) { totalVertices = null; }
  49223. if (this.sourceMesh) {
  49224. this.sourceMesh.setIndices(indices, totalVertices);
  49225. }
  49226. return this.sourceMesh;
  49227. };
  49228. /**
  49229. * Boolean : True if the mesh owns the requested kind of data.
  49230. */
  49231. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  49232. return this._sourceMesh.isVerticesDataPresent(kind);
  49233. };
  49234. /**
  49235. * Returns an array of indices (IndicesArray).
  49236. */
  49237. InstancedMesh.prototype.getIndices = function () {
  49238. return this._sourceMesh.getIndices();
  49239. };
  49240. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  49241. get: function () {
  49242. return this._sourceMesh._positions;
  49243. },
  49244. enumerable: true,
  49245. configurable: true
  49246. });
  49247. /**
  49248. * Sets a new updated BoundingInfo to the mesh.
  49249. * Returns the mesh.
  49250. */
  49251. InstancedMesh.prototype.refreshBoundingInfo = function () {
  49252. var meshBB = this._sourceMesh.getBoundingInfo();
  49253. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  49254. this._updateBoundingInfo();
  49255. return this;
  49256. };
  49257. InstancedMesh.prototype._preActivate = function () {
  49258. if (this._currentLOD) {
  49259. this._currentLOD._preActivate();
  49260. }
  49261. return this;
  49262. };
  49263. InstancedMesh.prototype._activate = function (renderId) {
  49264. if (this._currentLOD) {
  49265. this._currentLOD._registerInstanceForRenderId(this, renderId);
  49266. }
  49267. return this;
  49268. };
  49269. /**
  49270. * Returns the current associated LOD AbstractMesh.
  49271. */
  49272. InstancedMesh.prototype.getLOD = function (camera) {
  49273. if (!camera) {
  49274. return this;
  49275. }
  49276. var boundingInfo = this.getBoundingInfo();
  49277. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  49278. if (this._currentLOD === this.sourceMesh) {
  49279. return this;
  49280. }
  49281. return this._currentLOD;
  49282. };
  49283. InstancedMesh.prototype._syncSubMeshes = function () {
  49284. this.releaseSubMeshes();
  49285. if (this._sourceMesh.subMeshes) {
  49286. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  49287. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  49288. }
  49289. }
  49290. return this;
  49291. };
  49292. InstancedMesh.prototype._generatePointsArray = function () {
  49293. return this._sourceMesh._generatePointsArray();
  49294. };
  49295. /**
  49296. * Creates a new InstancedMesh from the current mesh.
  49297. * - name (string) : the cloned mesh name
  49298. * - newParent (optional Node) : the optional Node to parent the clone to.
  49299. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  49300. *
  49301. * Returns the clone.
  49302. */
  49303. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  49304. var result = this._sourceMesh.createInstance(name);
  49305. // Deep copy
  49306. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  49307. // Bounding info
  49308. this.refreshBoundingInfo();
  49309. // Parent
  49310. if (newParent) {
  49311. result.parent = newParent;
  49312. }
  49313. if (!doNotCloneChildren) {
  49314. // Children
  49315. for (var index = 0; index < this.getScene().meshes.length; index++) {
  49316. var mesh = this.getScene().meshes[index];
  49317. if (mesh.parent === this) {
  49318. mesh.clone(mesh.name, result);
  49319. }
  49320. }
  49321. }
  49322. result.computeWorldMatrix(true);
  49323. return result;
  49324. };
  49325. /**
  49326. * Disposes the InstancedMesh.
  49327. * Returns nothing.
  49328. */
  49329. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  49330. // Remove from mesh
  49331. var index = this._sourceMesh.instances.indexOf(this);
  49332. this._sourceMesh.instances.splice(index, 1);
  49333. _super.prototype.dispose.call(this, doNotRecurse);
  49334. };
  49335. return InstancedMesh;
  49336. }(BABYLON.AbstractMesh));
  49337. BABYLON.InstancedMesh = InstancedMesh;
  49338. })(BABYLON || (BABYLON = {}));
  49339. //# sourceMappingURL=babylon.instancedMesh.js.map
  49340. var BABYLON;
  49341. (function (BABYLON) {
  49342. var LinesMesh = /** @class */ (function (_super) {
  49343. __extends(LinesMesh, _super);
  49344. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  49345. if (scene === void 0) { scene = null; }
  49346. if (parent === void 0) { parent = null; }
  49347. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  49348. _this.useVertexColor = useVertexColor;
  49349. _this.useVertexAlpha = useVertexAlpha;
  49350. _this.color = new BABYLON.Color3(1, 1, 1);
  49351. _this.alpha = 1;
  49352. if (source) {
  49353. _this.color = source.color.clone();
  49354. _this.alpha = source.alpha;
  49355. _this.useVertexColor = source.useVertexColor;
  49356. _this.useVertexAlpha = source.useVertexAlpha;
  49357. }
  49358. _this._intersectionThreshold = 0.1;
  49359. var defines = [];
  49360. var options = {
  49361. attributes: [BABYLON.VertexBuffer.PositionKind],
  49362. uniforms: ["world", "viewProjection"],
  49363. needAlphaBlending: true,
  49364. defines: defines
  49365. };
  49366. if (useVertexAlpha === false) {
  49367. options.needAlphaBlending = false;
  49368. }
  49369. if (!useVertexColor) {
  49370. options.uniforms.push("color");
  49371. }
  49372. else {
  49373. options.defines.push("#define VERTEXCOLOR");
  49374. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  49375. }
  49376. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  49377. return _this;
  49378. }
  49379. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  49380. /**
  49381. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  49382. * This margin is expressed in world space coordinates, so its value may vary.
  49383. * Default value is 0.1
  49384. * @returns the intersection Threshold value.
  49385. */
  49386. get: function () {
  49387. return this._intersectionThreshold;
  49388. },
  49389. /**
  49390. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  49391. * This margin is expressed in world space coordinates, so its value may vary.
  49392. * @param value the new threshold to apply
  49393. */
  49394. set: function (value) {
  49395. if (this._intersectionThreshold === value) {
  49396. return;
  49397. }
  49398. this._intersectionThreshold = value;
  49399. if (this.geometry) {
  49400. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  49401. }
  49402. },
  49403. enumerable: true,
  49404. configurable: true
  49405. });
  49406. /**
  49407. * Returns the string "LineMesh"
  49408. */
  49409. LinesMesh.prototype.getClassName = function () {
  49410. return "LinesMesh";
  49411. };
  49412. Object.defineProperty(LinesMesh.prototype, "material", {
  49413. get: function () {
  49414. return this._colorShader;
  49415. },
  49416. set: function (value) {
  49417. // Do nothing
  49418. },
  49419. enumerable: true,
  49420. configurable: true
  49421. });
  49422. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  49423. get: function () {
  49424. return false;
  49425. },
  49426. enumerable: true,
  49427. configurable: true
  49428. });
  49429. LinesMesh.prototype.createInstance = function (name) {
  49430. throw new Error("LinesMeshes do not support createInstance.");
  49431. };
  49432. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  49433. if (!this._geometry) {
  49434. return this;
  49435. }
  49436. // VBOs
  49437. this._geometry._bind(this._colorShader.getEffect());
  49438. // Color
  49439. if (!this.useVertexColor) {
  49440. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  49441. }
  49442. return this;
  49443. };
  49444. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  49445. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  49446. return this;
  49447. }
  49448. var engine = this.getScene().getEngine();
  49449. // Draw order
  49450. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  49451. return this;
  49452. };
  49453. LinesMesh.prototype.dispose = function (doNotRecurse) {
  49454. this._colorShader.dispose();
  49455. _super.prototype.dispose.call(this, doNotRecurse);
  49456. };
  49457. /**
  49458. * Returns a new LineMesh object cloned from the current one.
  49459. */
  49460. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  49461. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  49462. };
  49463. return LinesMesh;
  49464. }(BABYLON.Mesh));
  49465. BABYLON.LinesMesh = LinesMesh;
  49466. })(BABYLON || (BABYLON = {}));
  49467. //# sourceMappingURL=babylon.linesMesh.js.map
  49468. var BABYLON;
  49469. (function (BABYLON) {
  49470. var MeshBuilder = /** @class */ (function () {
  49471. function MeshBuilder() {
  49472. }
  49473. MeshBuilder.updateSideOrientation = function (orientation) {
  49474. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  49475. return BABYLON.Mesh.DOUBLESIDE;
  49476. }
  49477. if (orientation === undefined || orientation === null) {
  49478. return BABYLON.Mesh.FRONTSIDE;
  49479. }
  49480. return orientation;
  49481. };
  49482. /**
  49483. * Creates a box mesh.
  49484. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  49485. * The parameter `size` sets the size (float) of each box side (default 1).
  49486. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  49487. * 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).
  49488. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  49489. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49490. * 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).
  49491. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49492. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49493. */
  49494. MeshBuilder.CreateBox = function (name, options, scene) {
  49495. if (scene === void 0) { scene = null; }
  49496. var box = new BABYLON.Mesh(name, scene);
  49497. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49498. box._originalBuilderSideOrientation = options.sideOrientation;
  49499. var vertexData = BABYLON.VertexData.CreateBox(options);
  49500. vertexData.applyToMesh(box, options.updatable);
  49501. return box;
  49502. };
  49503. /**
  49504. * Creates a sphere mesh.
  49505. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  49506. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  49507. * 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`).
  49508. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  49509. * 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
  49510. * 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).
  49511. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49512. * 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).
  49513. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49514. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49515. */
  49516. MeshBuilder.CreateSphere = function (name, options, scene) {
  49517. var sphere = new BABYLON.Mesh(name, scene);
  49518. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49519. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49520. var vertexData = BABYLON.VertexData.CreateSphere(options);
  49521. vertexData.applyToMesh(sphere, options.updatable);
  49522. return sphere;
  49523. };
  49524. /**
  49525. * Creates a plane polygonal mesh. By default, this is a disc.
  49526. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  49527. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  49528. * 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.
  49529. * 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
  49530. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49531. * 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).
  49532. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49533. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49534. */
  49535. MeshBuilder.CreateDisc = function (name, options, scene) {
  49536. if (scene === void 0) { scene = null; }
  49537. var disc = new BABYLON.Mesh(name, scene);
  49538. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49539. disc._originalBuilderSideOrientation = options.sideOrientation;
  49540. var vertexData = BABYLON.VertexData.CreateDisc(options);
  49541. vertexData.applyToMesh(disc, options.updatable);
  49542. return disc;
  49543. };
  49544. /**
  49545. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  49546. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  49547. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  49548. * 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`).
  49549. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  49550. * 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.
  49551. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49552. * 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).
  49553. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49554. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49555. */
  49556. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  49557. var sphere = new BABYLON.Mesh(name, scene);
  49558. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49559. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49560. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  49561. vertexData.applyToMesh(sphere, options.updatable);
  49562. return sphere;
  49563. };
  49564. ;
  49565. /**
  49566. * Creates a ribbon mesh.
  49567. * 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.
  49568. *
  49569. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  49570. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  49571. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  49572. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  49573. * 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.
  49574. * 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.
  49575. * 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
  49576. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49577. * 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).
  49578. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49579. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49580. * 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.
  49581. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  49582. * 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
  49583. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  49584. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  49585. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49586. */
  49587. MeshBuilder.CreateRibbon = function (name, options, scene) {
  49588. if (scene === void 0) { scene = null; }
  49589. var pathArray = options.pathArray;
  49590. var closeArray = options.closeArray;
  49591. var closePath = options.closePath;
  49592. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49593. var instance = options.instance;
  49594. var updatable = options.updatable;
  49595. if (instance) {
  49596. // positionFunction : ribbon case
  49597. // only pathArray and sideOrientation parameters are taken into account for positions update
  49598. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  49599. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  49600. var positionFunction = function (positions) {
  49601. var minlg = pathArray[0].length;
  49602. var i = 0;
  49603. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  49604. for (var si = 1; si <= ns; si++) {
  49605. for (var p = 0; p < pathArray.length; p++) {
  49606. var path = pathArray[p];
  49607. var l = path.length;
  49608. minlg = (minlg < l) ? minlg : l;
  49609. var j = 0;
  49610. while (j < minlg) {
  49611. positions[i] = path[j].x;
  49612. positions[i + 1] = path[j].y;
  49613. positions[i + 2] = path[j].z;
  49614. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  49615. BABYLON.Tmp.Vector3[0].x = path[j].x;
  49616. }
  49617. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  49618. BABYLON.Tmp.Vector3[1].x = path[j].x;
  49619. }
  49620. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  49621. BABYLON.Tmp.Vector3[0].y = path[j].y;
  49622. }
  49623. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  49624. BABYLON.Tmp.Vector3[1].y = path[j].y;
  49625. }
  49626. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  49627. BABYLON.Tmp.Vector3[0].z = path[j].z;
  49628. }
  49629. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  49630. BABYLON.Tmp.Vector3[1].z = path[j].z;
  49631. }
  49632. j++;
  49633. i += 3;
  49634. }
  49635. if (instance._closePath) {
  49636. positions[i] = path[0].x;
  49637. positions[i + 1] = path[0].y;
  49638. positions[i + 2] = path[0].z;
  49639. i += 3;
  49640. }
  49641. }
  49642. }
  49643. };
  49644. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49645. positionFunction(positions);
  49646. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  49647. instance._boundingInfo.update(instance._worldMatrix);
  49648. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49649. if (options.colors) {
  49650. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49651. for (var c = 0; c < options.colors.length; c++) {
  49652. colors[c * 4] = options.colors[c].r;
  49653. colors[c * 4 + 1] = options.colors[c].g;
  49654. colors[c * 4 + 2] = options.colors[c].b;
  49655. colors[c * 4 + 3] = options.colors[c].a;
  49656. }
  49657. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  49658. }
  49659. if (options.uvs) {
  49660. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49661. for (var i = 0; i < options.uvs.length; i++) {
  49662. uvs[i * 2] = options.uvs[i].x;
  49663. uvs[i * 2 + 1] = options.uvs[i].y;
  49664. }
  49665. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  49666. }
  49667. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  49668. var indices = instance.getIndices();
  49669. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49670. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  49671. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  49672. if (instance._closePath) {
  49673. var indexFirst = 0;
  49674. var indexLast = 0;
  49675. for (var p = 0; p < pathArray.length; p++) {
  49676. indexFirst = instance._idx[p] * 3;
  49677. if (p + 1 < pathArray.length) {
  49678. indexLast = (instance._idx[p + 1] - 1) * 3;
  49679. }
  49680. else {
  49681. indexLast = normals.length - 3;
  49682. }
  49683. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  49684. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  49685. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  49686. normals[indexLast] = normals[indexFirst];
  49687. normals[indexLast + 1] = normals[indexFirst + 1];
  49688. normals[indexLast + 2] = normals[indexFirst + 2];
  49689. }
  49690. }
  49691. if (!(instance.areNormalsFrozen)) {
  49692. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  49693. }
  49694. }
  49695. return instance;
  49696. }
  49697. else {
  49698. var ribbon = new BABYLON.Mesh(name, scene);
  49699. ribbon._originalBuilderSideOrientation = sideOrientation;
  49700. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  49701. if (closePath) {
  49702. ribbon._idx = vertexData._idx;
  49703. }
  49704. ribbon._closePath = closePath;
  49705. ribbon._closeArray = closeArray;
  49706. vertexData.applyToMesh(ribbon, updatable);
  49707. return ribbon;
  49708. }
  49709. };
  49710. /**
  49711. * Creates a cylinder or a cone mesh.
  49712. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  49713. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  49714. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  49715. * 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.
  49716. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  49717. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  49718. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  49719. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  49720. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  49721. * 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).
  49722. * 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
  49723. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  49724. * 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
  49725. * 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.
  49726. * If `enclose` is false, a ring surface is one element.
  49727. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  49728. * 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
  49729. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49730. * 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).
  49731. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49732. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49733. */
  49734. MeshBuilder.CreateCylinder = function (name, options, scene) {
  49735. var cylinder = new BABYLON.Mesh(name, scene);
  49736. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49737. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  49738. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  49739. vertexData.applyToMesh(cylinder, options.updatable);
  49740. return cylinder;
  49741. };
  49742. /**
  49743. * Creates a torus mesh.
  49744. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  49745. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  49746. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  49747. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  49748. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49749. * 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).
  49750. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49751. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49752. */
  49753. MeshBuilder.CreateTorus = function (name, options, scene) {
  49754. var torus = new BABYLON.Mesh(name, scene);
  49755. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49756. torus._originalBuilderSideOrientation = options.sideOrientation;
  49757. var vertexData = BABYLON.VertexData.CreateTorus(options);
  49758. vertexData.applyToMesh(torus, options.updatable);
  49759. return torus;
  49760. };
  49761. /**
  49762. * Creates a torus knot mesh.
  49763. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  49764. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  49765. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  49766. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  49767. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  49768. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49769. * 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).
  49770. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49771. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49772. */
  49773. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  49774. var torusKnot = new BABYLON.Mesh(name, scene);
  49775. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49776. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  49777. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  49778. vertexData.applyToMesh(torusKnot, options.updatable);
  49779. return torusKnot;
  49780. };
  49781. /**
  49782. * Creates a line system mesh.
  49783. * A line system is a pool of many lines gathered in a single mesh.
  49784. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  49785. * 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.
  49786. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  49787. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  49788. * 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
  49789. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  49790. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  49791. * 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
  49792. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  49793. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49794. */
  49795. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  49796. var instance = options.instance;
  49797. var lines = options.lines;
  49798. var colors = options.colors;
  49799. if (instance) {
  49800. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49801. var vertexColor;
  49802. var lineColors;
  49803. if (colors) {
  49804. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49805. }
  49806. var i = 0;
  49807. var c = 0;
  49808. for (var l = 0; l < lines.length; l++) {
  49809. var points = lines[l];
  49810. for (var p = 0; p < points.length; p++) {
  49811. positions[i] = points[p].x;
  49812. positions[i + 1] = points[p].y;
  49813. positions[i + 2] = points[p].z;
  49814. if (colors && vertexColor) {
  49815. lineColors = colors[l];
  49816. vertexColor[c] = lineColors[p].r;
  49817. vertexColor[c + 1] = lineColors[p].g;
  49818. vertexColor[c + 2] = lineColors[p].b;
  49819. vertexColor[c + 3] = lineColors[p].a;
  49820. c += 4;
  49821. }
  49822. i += 3;
  49823. }
  49824. }
  49825. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49826. if (colors && vertexColor) {
  49827. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  49828. }
  49829. return instance;
  49830. }
  49831. // line system creation
  49832. var useVertexColor = (colors) ? true : false;
  49833. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  49834. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  49835. vertexData.applyToMesh(lineSystem, options.updatable);
  49836. return lineSystem;
  49837. };
  49838. /**
  49839. * Creates a line mesh.
  49840. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  49841. * 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.
  49842. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49843. * The parameter `points` is an array successive Vector3.
  49844. * 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
  49845. * The optional parameter `colors` is an array of successive Color4, one per line point.
  49846. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  49847. * When updating an instance, remember that only point positions can change, not the number of points.
  49848. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49849. */
  49850. MeshBuilder.CreateLines = function (name, options, scene) {
  49851. if (scene === void 0) { scene = null; }
  49852. var colors = (options.colors) ? [options.colors] : null;
  49853. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  49854. return lines;
  49855. };
  49856. /**
  49857. * Creates a dashed line mesh.
  49858. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  49859. * 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.
  49860. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49861. * The parameter `points` is an array successive Vector3.
  49862. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  49863. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  49864. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  49865. * 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
  49866. * When updating an instance, remember that only point positions can change, not the number of points.
  49867. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49868. */
  49869. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  49870. if (scene === void 0) { scene = null; }
  49871. var points = options.points;
  49872. var instance = options.instance;
  49873. var gapSize = options.gapSize || 1;
  49874. var dashSize = options.dashSize || 3;
  49875. if (instance) {
  49876. var positionFunction = function (positions) {
  49877. var curvect = BABYLON.Vector3.Zero();
  49878. var nbSeg = positions.length / 6;
  49879. var lg = 0;
  49880. var nb = 0;
  49881. var shft = 0;
  49882. var dashshft = 0;
  49883. var curshft = 0;
  49884. var p = 0;
  49885. var i = 0;
  49886. var j = 0;
  49887. for (i = 0; i < points.length - 1; i++) {
  49888. points[i + 1].subtractToRef(points[i], curvect);
  49889. lg += curvect.length();
  49890. }
  49891. shft = lg / nbSeg;
  49892. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  49893. for (i = 0; i < points.length - 1; i++) {
  49894. points[i + 1].subtractToRef(points[i], curvect);
  49895. nb = Math.floor(curvect.length() / shft);
  49896. curvect.normalize();
  49897. j = 0;
  49898. while (j < nb && p < positions.length) {
  49899. curshft = shft * j;
  49900. positions[p] = points[i].x + curshft * curvect.x;
  49901. positions[p + 1] = points[i].y + curshft * curvect.y;
  49902. positions[p + 2] = points[i].z + curshft * curvect.z;
  49903. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  49904. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  49905. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  49906. p += 6;
  49907. j++;
  49908. }
  49909. }
  49910. while (p < positions.length) {
  49911. positions[p] = points[i].x;
  49912. positions[p + 1] = points[i].y;
  49913. positions[p + 2] = points[i].z;
  49914. p += 3;
  49915. }
  49916. };
  49917. instance.updateMeshPositions(positionFunction, false);
  49918. return instance;
  49919. }
  49920. // dashed lines creation
  49921. var dashedLines = new BABYLON.LinesMesh(name, scene);
  49922. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  49923. vertexData.applyToMesh(dashedLines, options.updatable);
  49924. dashedLines.dashSize = dashSize;
  49925. dashedLines.gapSize = gapSize;
  49926. return dashedLines;
  49927. };
  49928. /**
  49929. * Creates an extruded shape mesh.
  49930. * 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.
  49931. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  49932. *
  49933. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49934. * 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
  49935. * extruded along the Z axis.
  49936. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49937. * 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.
  49938. * The parameter `scale` (float, default 1) is the value to scale the shape.
  49939. * 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
  49940. * 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
  49941. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49942. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49943. * 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).
  49944. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49945. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49946. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49947. */
  49948. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  49949. if (scene === void 0) { scene = null; }
  49950. var path = options.path;
  49951. var shape = options.shape;
  49952. var scale = options.scale || 1;
  49953. var rotation = options.rotation || 0;
  49954. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49955. var updatable = options.updatable;
  49956. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49957. var instance = options.instance || null;
  49958. var invertUV = options.invertUV || false;
  49959. 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);
  49960. };
  49961. /**
  49962. * Creates an custom extruded shape mesh.
  49963. * 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.
  49964. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  49965. *
  49966. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49967. * 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
  49968. * extruded along the Z axis.
  49969. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49970. * 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
  49971. * and the distance of this point from the begining of the path :
  49972. * ```javascript
  49973. * var rotationFunction = function(i, distance) {
  49974. * // do things
  49975. * return rotationValue; }
  49976. * ```
  49977. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  49978. * 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
  49979. * and the distance of this point from the begining of the path :
  49980. * ```javascript
  49981. * var scaleFunction = function(i, distance) {
  49982. * // do things
  49983. * return scaleValue;}
  49984. * ```
  49985. * It must returns a float value that will be the scale value applied to the shape on each path point.
  49986. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  49987. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  49988. * 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
  49989. * 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
  49990. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49991. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49992. * 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).
  49993. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49994. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49996. */
  49997. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  49998. var path = options.path;
  49999. var shape = options.shape;
  50000. var scaleFunction = options.scaleFunction || (function () { return 1; });
  50001. var rotationFunction = options.rotationFunction || (function () { return 0; });
  50002. var ribbonCloseArray = options.ribbonCloseArray || false;
  50003. var ribbonClosePath = options.ribbonClosePath || false;
  50004. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  50005. var updatable = options.updatable;
  50006. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50007. var instance = options.instance;
  50008. var invertUV = options.invertUV || false;
  50009. 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);
  50010. };
  50011. /**
  50012. * Creates lathe mesh.
  50013. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  50014. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  50015. *
  50016. * 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
  50017. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  50018. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  50019. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  50020. * 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.
  50021. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  50022. * 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
  50023. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50024. * 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).
  50025. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50026. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  50027. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50028. */
  50029. MeshBuilder.CreateLathe = function (name, options, scene) {
  50030. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  50031. var closed = (options.closed === undefined) ? true : options.closed;
  50032. var shape = options.shape;
  50033. var radius = options.radius || 1;
  50034. var tessellation = options.tessellation || 64;
  50035. var updatable = options.updatable;
  50036. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50037. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  50038. var pi2 = Math.PI * 2;
  50039. var paths = new Array();
  50040. var invertUV = options.invertUV || false;
  50041. var i = 0;
  50042. var p = 0;
  50043. var step = pi2 / tessellation * arc;
  50044. var rotated;
  50045. var path = new Array();
  50046. ;
  50047. for (i = 0; i <= tessellation; i++) {
  50048. var path = [];
  50049. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  50050. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  50051. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  50052. }
  50053. for (p = 0; p < shape.length; p++) {
  50054. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  50055. path.push(rotated);
  50056. }
  50057. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  50058. 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));
  50059. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  50060. }
  50061. paths.push(path);
  50062. }
  50063. // lathe ribbon
  50064. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  50065. return lathe;
  50066. };
  50067. /**
  50068. * Creates a plane mesh.
  50069. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  50070. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  50071. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  50072. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  50073. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50074. * 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).
  50075. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50076. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50077. */
  50078. MeshBuilder.CreatePlane = function (name, options, scene) {
  50079. var plane = new BABYLON.Mesh(name, scene);
  50080. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50081. plane._originalBuilderSideOrientation = options.sideOrientation;
  50082. var vertexData = BABYLON.VertexData.CreatePlane(options);
  50083. vertexData.applyToMesh(plane, options.updatable);
  50084. if (options.sourcePlane) {
  50085. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  50086. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  50087. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  50088. plane.rotate(vectorProduct, product);
  50089. }
  50090. return plane;
  50091. };
  50092. /**
  50093. * Creates a ground mesh.
  50094. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  50095. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  50096. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  50097. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50098. */
  50099. MeshBuilder.CreateGround = function (name, options, scene) {
  50100. var ground = new BABYLON.GroundMesh(name, scene);
  50101. ground._setReady(false);
  50102. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  50103. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  50104. ground._width = options.width || 1;
  50105. ground._height = options.height || 1;
  50106. ground._maxX = ground._width / 2;
  50107. ground._maxZ = ground._height / 2;
  50108. ground._minX = -ground._maxX;
  50109. ground._minZ = -ground._maxZ;
  50110. var vertexData = BABYLON.VertexData.CreateGround(options);
  50111. vertexData.applyToMesh(ground, options.updatable);
  50112. ground._setReady(true);
  50113. return ground;
  50114. };
  50115. /**
  50116. * Creates a tiled ground mesh.
  50117. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  50118. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  50119. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  50120. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  50121. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  50122. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  50123. * numbers of subdivisions on the ground width and height of each tile.
  50124. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50125. */
  50126. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  50127. var tiledGround = new BABYLON.Mesh(name, scene);
  50128. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  50129. vertexData.applyToMesh(tiledGround, options.updatable);
  50130. return tiledGround;
  50131. };
  50132. /**
  50133. * Creates a ground mesh from a height map.
  50134. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  50135. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  50136. * The parameter `url` sets the URL of the height map image resource.
  50137. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  50138. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  50139. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  50140. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  50141. * 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.
  50142. * 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).
  50143. * This function is passed the newly built mesh :
  50144. * ```javascript
  50145. * function(mesh) { // do things
  50146. * return; }
  50147. * ```
  50148. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50149. */
  50150. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  50151. var width = options.width || 10.0;
  50152. var height = options.height || 10.0;
  50153. var subdivisions = options.subdivisions || 1 | 0;
  50154. var minHeight = options.minHeight || 0.0;
  50155. var maxHeight = options.maxHeight || 1.0;
  50156. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  50157. var updatable = options.updatable;
  50158. var onReady = options.onReady;
  50159. var ground = new BABYLON.GroundMesh(name, scene);
  50160. ground._subdivisionsX = subdivisions;
  50161. ground._subdivisionsY = subdivisions;
  50162. ground._width = width;
  50163. ground._height = height;
  50164. ground._maxX = ground._width / 2.0;
  50165. ground._maxZ = ground._height / 2.0;
  50166. ground._minX = -ground._maxX;
  50167. ground._minZ = -ground._maxZ;
  50168. ground._setReady(false);
  50169. var onload = function (img) {
  50170. // Getting height map data
  50171. var canvas = document.createElement("canvas");
  50172. var context = canvas.getContext("2d");
  50173. if (!context) {
  50174. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  50175. }
  50176. if (scene.isDisposed) {
  50177. return;
  50178. }
  50179. var bufferWidth = img.width;
  50180. var bufferHeight = img.height;
  50181. canvas.width = bufferWidth;
  50182. canvas.height = bufferHeight;
  50183. context.drawImage(img, 0, 0);
  50184. // Create VertexData from map data
  50185. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  50186. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  50187. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  50188. width: width, height: height,
  50189. subdivisions: subdivisions,
  50190. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  50191. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  50192. });
  50193. vertexData.applyToMesh(ground, updatable);
  50194. ground._setReady(true);
  50195. //execute ready callback, if set
  50196. if (onReady) {
  50197. onReady(ground);
  50198. }
  50199. };
  50200. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  50201. return ground;
  50202. };
  50203. /**
  50204. * Creates a polygon mesh.
  50205. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  50206. * 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.
  50207. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50208. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50209. * 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).
  50210. * Remember you can only change the shape positions, not their number when updating a polygon.
  50211. */
  50212. MeshBuilder.CreatePolygon = function (name, options, scene) {
  50213. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50214. var shape = options.shape;
  50215. var holes = options.holes || [];
  50216. var depth = options.depth || 0;
  50217. var contours = [];
  50218. var hole = [];
  50219. for (var i = 0; i < shape.length; i++) {
  50220. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  50221. }
  50222. var epsilon = 0.00000001;
  50223. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  50224. contours.pop();
  50225. }
  50226. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  50227. for (var hNb = 0; hNb < holes.length; hNb++) {
  50228. hole = [];
  50229. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  50230. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  50231. }
  50232. polygonTriangulation.addHole(hole);
  50233. }
  50234. var polygon = polygonTriangulation.build(options.updatable, depth);
  50235. polygon._originalBuilderSideOrientation = options.sideOrientation;
  50236. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  50237. vertexData.applyToMesh(polygon, options.updatable);
  50238. return polygon;
  50239. };
  50240. ;
  50241. /**
  50242. * Creates an extruded polygon mesh, with depth in the Y direction.
  50243. * 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).
  50244. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  50245. */
  50246. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  50247. return MeshBuilder.CreatePolygon(name, options, scene);
  50248. };
  50249. ;
  50250. /**
  50251. * Creates a tube mesh.
  50252. * 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.
  50253. *
  50254. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  50255. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  50256. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  50257. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  50258. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  50259. * 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.
  50260. * It must return a radius value (positive float) :
  50261. * ```javascript
  50262. * var radiusFunction = function(i, distance) {
  50263. * // do things
  50264. * return radius; }
  50265. * ```
  50266. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  50267. * 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
  50268. * 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
  50269. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50270. * 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).
  50271. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50272. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  50273. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50274. */
  50275. MeshBuilder.CreateTube = function (name, options, scene) {
  50276. var path = options.path;
  50277. var instance = options.instance;
  50278. var radius = 1.0;
  50279. if (instance) {
  50280. radius = instance.radius;
  50281. }
  50282. if (options.radius !== undefined) {
  50283. radius = options.radius;
  50284. }
  50285. ;
  50286. var tessellation = options.tessellation || 64 | 0;
  50287. var radiusFunction = options.radiusFunction || null;
  50288. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  50289. var invertUV = options.invertUV || false;
  50290. var updatable = options.updatable;
  50291. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50292. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  50293. // tube geometry
  50294. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  50295. var tangents = path3D.getTangents();
  50296. var normals = path3D.getNormals();
  50297. var distances = path3D.getDistances();
  50298. var pi2 = Math.PI * 2;
  50299. var step = pi2 / tessellation * arc;
  50300. var returnRadius = function () { return radius; };
  50301. var radiusFunctionFinal = radiusFunction || returnRadius;
  50302. var circlePath;
  50303. var rad;
  50304. var normal;
  50305. var rotated;
  50306. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  50307. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  50308. for (var i = 0; i < path.length; i++) {
  50309. rad = radiusFunctionFinal(i, distances[i]); // current radius
  50310. circlePath = Array(); // current circle array
  50311. normal = normals[i]; // current normal
  50312. for (var t = 0; t < tessellation; t++) {
  50313. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  50314. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  50315. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  50316. rotated.scaleInPlace(rad).addInPlace(path[i]);
  50317. circlePath[t] = rotated;
  50318. }
  50319. circlePaths[index] = circlePath;
  50320. index++;
  50321. }
  50322. // cap
  50323. var capPath = function (nbPoints, pathIndex) {
  50324. var pointCap = Array();
  50325. for (var i = 0; i < nbPoints; i++) {
  50326. pointCap.push(path[pathIndex]);
  50327. }
  50328. return pointCap;
  50329. };
  50330. switch (cap) {
  50331. case BABYLON.Mesh.NO_CAP:
  50332. break;
  50333. case BABYLON.Mesh.CAP_START:
  50334. circlePaths[0] = capPath(tessellation, 0);
  50335. circlePaths[1] = circlePaths[2].slice(0);
  50336. break;
  50337. case BABYLON.Mesh.CAP_END:
  50338. circlePaths[index] = circlePaths[index - 1].slice(0);
  50339. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  50340. break;
  50341. case BABYLON.Mesh.CAP_ALL:
  50342. circlePaths[0] = capPath(tessellation, 0);
  50343. circlePaths[1] = circlePaths[2].slice(0);
  50344. circlePaths[index] = circlePaths[index - 1].slice(0);
  50345. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  50346. break;
  50347. default:
  50348. break;
  50349. }
  50350. return circlePaths;
  50351. };
  50352. var path3D;
  50353. var pathArray;
  50354. if (instance) {
  50355. var arc = options.arc || instance.arc;
  50356. path3D = (instance.path3D).update(path);
  50357. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  50358. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  50359. instance.path3D = path3D;
  50360. instance.pathArray = pathArray;
  50361. instance.arc = arc;
  50362. instance.radius = radius;
  50363. return instance;
  50364. }
  50365. // tube creation
  50366. path3D = new BABYLON.Path3D(path);
  50367. var newPathArray = new Array();
  50368. cap = (cap < 0 || cap > 3) ? 0 : cap;
  50369. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  50370. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  50371. tube.pathArray = pathArray;
  50372. tube.path3D = path3D;
  50373. tube.tessellation = tessellation;
  50374. tube.cap = cap;
  50375. tube.arc = options.arc;
  50376. tube.radius = radius;
  50377. return tube;
  50378. };
  50379. /**
  50380. * Creates a polyhedron mesh.
  50381. *
  50382. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  50383. * 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
  50384. * to choose the wanted type.
  50385. * The parameter `size` (positive float, default 1) sets the polygon size.
  50386. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  50387. * 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`.
  50388. * 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
  50389. * 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)`).
  50390. * 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
  50391. * 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.
  50392. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50393. * 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).
  50394. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50395. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50396. */
  50397. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  50398. var polyhedron = new BABYLON.Mesh(name, scene);
  50399. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50400. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  50401. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  50402. vertexData.applyToMesh(polyhedron, options.updatable);
  50403. return polyhedron;
  50404. };
  50405. /**
  50406. * Creates a decal mesh.
  50407. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  50408. * 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.
  50409. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  50410. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  50411. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  50412. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  50413. */
  50414. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  50415. var indices = sourceMesh.getIndices();
  50416. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50417. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50418. var position = options.position || BABYLON.Vector3.Zero();
  50419. var normal = options.normal || BABYLON.Vector3.Up();
  50420. var size = options.size || BABYLON.Vector3.One();
  50421. var angle = options.angle || 0;
  50422. // Getting correct rotation
  50423. if (!normal) {
  50424. var target = new BABYLON.Vector3(0, 0, 1);
  50425. var camera = sourceMesh.getScene().activeCamera;
  50426. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  50427. normal = camera.globalPosition.subtract(cameraWorldTarget);
  50428. }
  50429. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  50430. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  50431. var pitch = Math.atan2(normal.y, len);
  50432. // Matrix
  50433. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  50434. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  50435. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  50436. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  50437. var vertexData = new BABYLON.VertexData();
  50438. vertexData.indices = [];
  50439. vertexData.positions = [];
  50440. vertexData.normals = [];
  50441. vertexData.uvs = [];
  50442. var currentVertexDataIndex = 0;
  50443. var extractDecalVector3 = function (indexId) {
  50444. var result = new BABYLON.PositionNormalVertex();
  50445. if (!indices || !positions || !normals) {
  50446. return result;
  50447. }
  50448. var vertexId = indices[indexId];
  50449. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  50450. // Send vector to decal local world
  50451. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  50452. // Get normal
  50453. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  50454. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  50455. return result;
  50456. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  50457. var clip = function (vertices, axis) {
  50458. if (vertices.length === 0) {
  50459. return vertices;
  50460. }
  50461. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  50462. var clipVertices = function (v0, v1) {
  50463. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  50464. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  50465. };
  50466. var result = new Array();
  50467. for (var index = 0; index < vertices.length; index += 3) {
  50468. var v1Out;
  50469. var v2Out;
  50470. var v3Out;
  50471. var total = 0;
  50472. var nV1 = null;
  50473. var nV2 = null;
  50474. var nV3 = null;
  50475. var nV4 = null;
  50476. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  50477. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  50478. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  50479. v1Out = d1 > 0;
  50480. v2Out = d2 > 0;
  50481. v3Out = d3 > 0;
  50482. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  50483. switch (total) {
  50484. case 0:
  50485. result.push(vertices[index]);
  50486. result.push(vertices[index + 1]);
  50487. result.push(vertices[index + 2]);
  50488. break;
  50489. case 1:
  50490. if (v1Out) {
  50491. nV1 = vertices[index + 1];
  50492. nV2 = vertices[index + 2];
  50493. nV3 = clipVertices(vertices[index], nV1);
  50494. nV4 = clipVertices(vertices[index], nV2);
  50495. }
  50496. if (v2Out) {
  50497. nV1 = vertices[index];
  50498. nV2 = vertices[index + 2];
  50499. nV3 = clipVertices(vertices[index + 1], nV1);
  50500. nV4 = clipVertices(vertices[index + 1], nV2);
  50501. result.push(nV3);
  50502. result.push(nV2.clone());
  50503. result.push(nV1.clone());
  50504. result.push(nV2.clone());
  50505. result.push(nV3.clone());
  50506. result.push(nV4);
  50507. break;
  50508. }
  50509. if (v3Out) {
  50510. nV1 = vertices[index];
  50511. nV2 = vertices[index + 1];
  50512. nV3 = clipVertices(vertices[index + 2], nV1);
  50513. nV4 = clipVertices(vertices[index + 2], nV2);
  50514. }
  50515. if (nV1 && nV2 && nV3 && nV4) {
  50516. result.push(nV1.clone());
  50517. result.push(nV2.clone());
  50518. result.push(nV3);
  50519. result.push(nV4);
  50520. result.push(nV3.clone());
  50521. result.push(nV2.clone());
  50522. }
  50523. break;
  50524. case 2:
  50525. if (!v1Out) {
  50526. nV1 = vertices[index].clone();
  50527. nV2 = clipVertices(nV1, vertices[index + 1]);
  50528. nV3 = clipVertices(nV1, vertices[index + 2]);
  50529. result.push(nV1);
  50530. result.push(nV2);
  50531. result.push(nV3);
  50532. }
  50533. if (!v2Out) {
  50534. nV1 = vertices[index + 1].clone();
  50535. nV2 = clipVertices(nV1, vertices[index + 2]);
  50536. nV3 = clipVertices(nV1, vertices[index]);
  50537. result.push(nV1);
  50538. result.push(nV2);
  50539. result.push(nV3);
  50540. }
  50541. if (!v3Out) {
  50542. nV1 = vertices[index + 2].clone();
  50543. nV2 = clipVertices(nV1, vertices[index]);
  50544. nV3 = clipVertices(nV1, vertices[index + 1]);
  50545. result.push(nV1);
  50546. result.push(nV2);
  50547. result.push(nV3);
  50548. }
  50549. break;
  50550. case 3:
  50551. break;
  50552. }
  50553. }
  50554. return result;
  50555. };
  50556. for (var index = 0; index < indices.length; index += 3) {
  50557. var faceVertices = new Array();
  50558. faceVertices.push(extractDecalVector3(index));
  50559. faceVertices.push(extractDecalVector3(index + 1));
  50560. faceVertices.push(extractDecalVector3(index + 2));
  50561. // Clip
  50562. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  50563. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  50564. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  50565. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  50566. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  50567. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  50568. if (faceVertices.length === 0) {
  50569. continue;
  50570. }
  50571. // Add UVs and get back to world
  50572. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  50573. var vertex = faceVertices[vIndex];
  50574. //TODO check for Int32Array | Uint32Array | Uint16Array
  50575. vertexData.indices.push(currentVertexDataIndex);
  50576. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  50577. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  50578. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  50579. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  50580. currentVertexDataIndex++;
  50581. }
  50582. }
  50583. // Return mesh
  50584. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  50585. vertexData.applyToMesh(decal);
  50586. decal.position = position.clone();
  50587. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  50588. return decal;
  50589. };
  50590. // Privates
  50591. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  50592. // extrusion geometry
  50593. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  50594. var tangents = path3D.getTangents();
  50595. var normals = path3D.getNormals();
  50596. var binormals = path3D.getBinormals();
  50597. var distances = path3D.getDistances();
  50598. var angle = 0;
  50599. var returnScale = function () { return scale !== null ? scale : 1; };
  50600. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  50601. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  50602. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  50603. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  50604. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  50605. for (var i = 0; i < curve.length; i++) {
  50606. var shapePath = new Array();
  50607. var angleStep = rotate(i, distances[i]);
  50608. var scaleRatio = scl(i, distances[i]);
  50609. for (var p = 0; p < shape.length; p++) {
  50610. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  50611. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  50612. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  50613. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  50614. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  50615. shapePath[p] = rotated;
  50616. }
  50617. shapePaths[index] = shapePath;
  50618. angle += angleStep;
  50619. index++;
  50620. }
  50621. // cap
  50622. var capPath = function (shapePath) {
  50623. var pointCap = Array();
  50624. var barycenter = BABYLON.Vector3.Zero();
  50625. var i;
  50626. for (i = 0; i < shapePath.length; i++) {
  50627. barycenter.addInPlace(shapePath[i]);
  50628. }
  50629. barycenter.scaleInPlace(1.0 / shapePath.length);
  50630. for (i = 0; i < shapePath.length; i++) {
  50631. pointCap.push(barycenter);
  50632. }
  50633. return pointCap;
  50634. };
  50635. switch (cap) {
  50636. case BABYLON.Mesh.NO_CAP:
  50637. break;
  50638. case BABYLON.Mesh.CAP_START:
  50639. shapePaths[0] = capPath(shapePaths[2]);
  50640. shapePaths[1] = shapePaths[2];
  50641. break;
  50642. case BABYLON.Mesh.CAP_END:
  50643. shapePaths[index] = shapePaths[index - 1];
  50644. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  50645. break;
  50646. case BABYLON.Mesh.CAP_ALL:
  50647. shapePaths[0] = capPath(shapePaths[2]);
  50648. shapePaths[1] = shapePaths[2];
  50649. shapePaths[index] = shapePaths[index - 1];
  50650. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  50651. break;
  50652. default:
  50653. break;
  50654. }
  50655. return shapePaths;
  50656. };
  50657. var path3D;
  50658. var pathArray;
  50659. if (instance) {
  50660. path3D = (instance.path3D).update(curve);
  50661. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  50662. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  50663. return instance;
  50664. }
  50665. // extruded shape creation
  50666. path3D = new BABYLON.Path3D(curve);
  50667. var newShapePaths = new Array();
  50668. cap = (cap < 0 || cap > 3) ? 0 : cap;
  50669. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  50670. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  50671. extrudedGeneric.pathArray = pathArray;
  50672. extrudedGeneric.path3D = path3D;
  50673. extrudedGeneric.cap = cap;
  50674. return extrudedGeneric;
  50675. };
  50676. return MeshBuilder;
  50677. }());
  50678. BABYLON.MeshBuilder = MeshBuilder;
  50679. })(BABYLON || (BABYLON = {}));
  50680. //# sourceMappingURL=babylon.meshBuilder.js.map
  50681. var BABYLON;
  50682. (function (BABYLON) {
  50683. var AudioEngine = /** @class */ (function () {
  50684. function AudioEngine() {
  50685. this._audioContext = null;
  50686. this._audioContextInitialized = false;
  50687. this.canUseWebAudio = false;
  50688. this.WarnedWebAudioUnsupported = false;
  50689. this.unlocked = false;
  50690. this.isMP3supported = false;
  50691. this.isOGGsupported = false;
  50692. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  50693. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  50694. this.canUseWebAudio = true;
  50695. }
  50696. var audioElem = document.createElement('audio');
  50697. try {
  50698. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  50699. this.isMP3supported = true;
  50700. }
  50701. }
  50702. catch (e) {
  50703. // protect error during capability check.
  50704. }
  50705. try {
  50706. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  50707. this.isOGGsupported = true;
  50708. }
  50709. }
  50710. catch (e) {
  50711. // protect error during capability check.
  50712. }
  50713. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  50714. this._unlockiOSaudio();
  50715. }
  50716. else {
  50717. this.unlocked = true;
  50718. }
  50719. }
  50720. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  50721. get: function () {
  50722. if (!this._audioContextInitialized) {
  50723. this._initializeAudioContext();
  50724. }
  50725. return this._audioContext;
  50726. },
  50727. enumerable: true,
  50728. configurable: true
  50729. });
  50730. AudioEngine.prototype._unlockiOSaudio = function () {
  50731. var _this = this;
  50732. var unlockaudio = function () {
  50733. if (!_this.audioContext) {
  50734. return;
  50735. }
  50736. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  50737. var source = _this.audioContext.createBufferSource();
  50738. source.buffer = buffer;
  50739. source.connect(_this.audioContext.destination);
  50740. source.start(0);
  50741. setTimeout(function () {
  50742. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  50743. _this.unlocked = true;
  50744. window.removeEventListener('touchend', unlockaudio, false);
  50745. if (_this.onAudioUnlocked) {
  50746. _this.onAudioUnlocked();
  50747. }
  50748. }
  50749. }, 0);
  50750. };
  50751. window.addEventListener('touchend', unlockaudio, false);
  50752. };
  50753. AudioEngine.prototype._initializeAudioContext = function () {
  50754. try {
  50755. if (this.canUseWebAudio) {
  50756. this._audioContext = new AudioContext();
  50757. // create a global volume gain node
  50758. this.masterGain = this._audioContext.createGain();
  50759. this.masterGain.gain.value = 1;
  50760. this.masterGain.connect(this._audioContext.destination);
  50761. this._audioContextInitialized = true;
  50762. }
  50763. }
  50764. catch (e) {
  50765. this.canUseWebAudio = false;
  50766. BABYLON.Tools.Error("Web Audio: " + e.message);
  50767. }
  50768. };
  50769. AudioEngine.prototype.dispose = function () {
  50770. if (this.canUseWebAudio && this._audioContextInitialized) {
  50771. if (this._connectedAnalyser && this._audioContext) {
  50772. this._connectedAnalyser.stopDebugCanvas();
  50773. this._connectedAnalyser.dispose();
  50774. this.masterGain.disconnect();
  50775. this.masterGain.connect(this._audioContext.destination);
  50776. this._connectedAnalyser = null;
  50777. }
  50778. this.masterGain.gain.value = 1;
  50779. }
  50780. this.WarnedWebAudioUnsupported = false;
  50781. };
  50782. AudioEngine.prototype.getGlobalVolume = function () {
  50783. if (this.canUseWebAudio && this._audioContextInitialized) {
  50784. return this.masterGain.gain.value;
  50785. }
  50786. else {
  50787. return -1;
  50788. }
  50789. };
  50790. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  50791. if (this.canUseWebAudio && this._audioContextInitialized) {
  50792. this.masterGain.gain.value = newVolume;
  50793. }
  50794. };
  50795. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  50796. if (this._connectedAnalyser) {
  50797. this._connectedAnalyser.stopDebugCanvas();
  50798. }
  50799. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  50800. this._connectedAnalyser = analyser;
  50801. this.masterGain.disconnect();
  50802. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  50803. }
  50804. };
  50805. return AudioEngine;
  50806. }());
  50807. BABYLON.AudioEngine = AudioEngine;
  50808. })(BABYLON || (BABYLON = {}));
  50809. //# sourceMappingURL=babylon.audioEngine.js.map
  50810. var BABYLON;
  50811. (function (BABYLON) {
  50812. var Sound = /** @class */ (function () {
  50813. /**
  50814. * Create a sound and attach it to a scene
  50815. * @param name Name of your sound
  50816. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  50817. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  50818. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  50819. */
  50820. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  50821. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  50822. var _this = this;
  50823. this.autoplay = false;
  50824. this.loop = false;
  50825. this.useCustomAttenuation = false;
  50826. this.spatialSound = false;
  50827. this.refDistance = 1;
  50828. this.rolloffFactor = 1;
  50829. this.maxDistance = 100;
  50830. this.distanceModel = "linear";
  50831. this._panningModel = "equalpower";
  50832. this._playbackRate = 1;
  50833. this._streaming = false;
  50834. this._startTime = 0;
  50835. this._startOffset = 0;
  50836. this._position = BABYLON.Vector3.Zero();
  50837. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  50838. this._volume = 1;
  50839. this._isReadyToPlay = false;
  50840. this.isPlaying = false;
  50841. this.isPaused = false;
  50842. this._isDirectional = false;
  50843. // Used if you'd like to create a directional sound.
  50844. // If not set, the sound will be omnidirectional
  50845. this._coneInnerAngle = 360;
  50846. this._coneOuterAngle = 360;
  50847. this._coneOuterGain = 0;
  50848. this._isOutputConnected = false;
  50849. this._urlType = "Unknown";
  50850. this.name = name;
  50851. this._scene = scene;
  50852. this._readyToPlayCallback = readyToPlayCallback;
  50853. // Default custom attenuation function is a linear attenuation
  50854. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  50855. if (currentDistance < maxDistance) {
  50856. return currentVolume * (1 - currentDistance / maxDistance);
  50857. }
  50858. else {
  50859. return 0;
  50860. }
  50861. };
  50862. if (options) {
  50863. this.autoplay = options.autoplay || false;
  50864. this.loop = options.loop || false;
  50865. // if volume === 0, we need another way to check this option
  50866. if (options.volume !== undefined) {
  50867. this._volume = options.volume;
  50868. }
  50869. this.spatialSound = options.spatialSound || false;
  50870. this.maxDistance = options.maxDistance || 100;
  50871. this.useCustomAttenuation = options.useCustomAttenuation || false;
  50872. this.rolloffFactor = options.rolloffFactor || 1;
  50873. this.refDistance = options.refDistance || 1;
  50874. this.distanceModel = options.distanceModel || "linear";
  50875. this._playbackRate = options.playbackRate || 1;
  50876. this._streaming = options.streaming || false;
  50877. }
  50878. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50879. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  50880. this._soundGain.gain.value = this._volume;
  50881. this._inputAudioNode = this._soundGain;
  50882. this._ouputAudioNode = this._soundGain;
  50883. if (this.spatialSound) {
  50884. this._createSpatialParameters();
  50885. }
  50886. this._scene.mainSoundTrack.AddSound(this);
  50887. var validParameter = true;
  50888. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  50889. if (urlOrArrayBuffer) {
  50890. if (typeof (urlOrArrayBuffer) === "string")
  50891. this._urlType = "String";
  50892. if (Array.isArray(urlOrArrayBuffer))
  50893. this._urlType = "Array";
  50894. if (urlOrArrayBuffer instanceof ArrayBuffer)
  50895. this._urlType = "ArrayBuffer";
  50896. var urls = [];
  50897. var codecSupportedFound = false;
  50898. switch (this._urlType) {
  50899. case "ArrayBuffer":
  50900. if (urlOrArrayBuffer.byteLength > 0) {
  50901. codecSupportedFound = true;
  50902. this._soundLoaded(urlOrArrayBuffer);
  50903. }
  50904. break;
  50905. case "String":
  50906. urls.push(urlOrArrayBuffer);
  50907. case "Array":
  50908. if (urls.length === 0)
  50909. urls = urlOrArrayBuffer;
  50910. // If we found a supported format, we load it immediately and stop the loop
  50911. for (var i = 0; i < urls.length; i++) {
  50912. var url = urls[i];
  50913. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  50914. codecSupportedFound = true;
  50915. }
  50916. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  50917. codecSupportedFound = true;
  50918. }
  50919. if (url.indexOf(".wav", url.length - 4) !== -1) {
  50920. codecSupportedFound = true;
  50921. }
  50922. if (url.indexOf("blob:") !== -1) {
  50923. codecSupportedFound = true;
  50924. }
  50925. if (codecSupportedFound) {
  50926. // Loading sound using XHR2
  50927. if (!this._streaming) {
  50928. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  50929. }
  50930. else {
  50931. this._htmlAudioElement = new Audio(url);
  50932. this._htmlAudioElement.controls = false;
  50933. this._htmlAudioElement.loop = this.loop;
  50934. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  50935. this._htmlAudioElement.preload = "auto";
  50936. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  50937. _this._isReadyToPlay = true;
  50938. if (_this.autoplay) {
  50939. _this.play();
  50940. }
  50941. if (_this._readyToPlayCallback) {
  50942. _this._readyToPlayCallback();
  50943. }
  50944. });
  50945. document.body.appendChild(this._htmlAudioElement);
  50946. }
  50947. break;
  50948. }
  50949. }
  50950. break;
  50951. default:
  50952. validParameter = false;
  50953. break;
  50954. }
  50955. if (!validParameter) {
  50956. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  50957. }
  50958. else {
  50959. if (!codecSupportedFound) {
  50960. this._isReadyToPlay = true;
  50961. // Simulating a ready to play event to avoid breaking code path
  50962. if (this._readyToPlayCallback) {
  50963. window.setTimeout(function () {
  50964. if (_this._readyToPlayCallback) {
  50965. _this._readyToPlayCallback();
  50966. }
  50967. }, 1000);
  50968. }
  50969. }
  50970. }
  50971. }
  50972. }
  50973. else {
  50974. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  50975. this._scene.mainSoundTrack.AddSound(this);
  50976. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  50977. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  50978. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  50979. }
  50980. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  50981. if (this._readyToPlayCallback) {
  50982. window.setTimeout(function () {
  50983. if (_this._readyToPlayCallback) {
  50984. _this._readyToPlayCallback();
  50985. }
  50986. }, 1000);
  50987. }
  50988. }
  50989. }
  50990. Sound.prototype.dispose = function () {
  50991. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  50992. if (this.isPlaying) {
  50993. this.stop();
  50994. }
  50995. this._isReadyToPlay = false;
  50996. if (this.soundTrackId === -1) {
  50997. this._scene.mainSoundTrack.RemoveSound(this);
  50998. }
  50999. else {
  51000. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  51001. }
  51002. if (this._soundGain) {
  51003. this._soundGain.disconnect();
  51004. this._soundGain = null;
  51005. }
  51006. if (this._soundPanner) {
  51007. this._soundPanner.disconnect();
  51008. this._soundPanner = null;
  51009. }
  51010. if (this._soundSource) {
  51011. this._soundSource.disconnect();
  51012. this._soundSource = null;
  51013. }
  51014. this._audioBuffer = null;
  51015. if (this._htmlAudioElement) {
  51016. this._htmlAudioElement.pause();
  51017. this._htmlAudioElement.src = "";
  51018. document.body.removeChild(this._htmlAudioElement);
  51019. }
  51020. if (this._connectedMesh && this._registerFunc) {
  51021. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  51022. this._connectedMesh = null;
  51023. }
  51024. }
  51025. };
  51026. Sound.prototype.isReady = function () {
  51027. return this._isReadyToPlay;
  51028. };
  51029. Sound.prototype._soundLoaded = function (audioData) {
  51030. var _this = this;
  51031. if (!BABYLON.Engine.audioEngine.audioContext) {
  51032. return;
  51033. }
  51034. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  51035. _this._audioBuffer = buffer;
  51036. _this._isReadyToPlay = true;
  51037. if (_this.autoplay) {
  51038. _this.play();
  51039. }
  51040. if (_this._readyToPlayCallback) {
  51041. _this._readyToPlayCallback();
  51042. }
  51043. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  51044. };
  51045. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  51046. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51047. this._audioBuffer = audioBuffer;
  51048. this._isReadyToPlay = true;
  51049. }
  51050. };
  51051. Sound.prototype.updateOptions = function (options) {
  51052. if (options) {
  51053. this.loop = options.loop || this.loop;
  51054. this.maxDistance = options.maxDistance || this.maxDistance;
  51055. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  51056. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  51057. this.refDistance = options.refDistance || this.refDistance;
  51058. this.distanceModel = options.distanceModel || this.distanceModel;
  51059. this._playbackRate = options.playbackRate || this._playbackRate;
  51060. this._updateSpatialParameters();
  51061. if (this.isPlaying) {
  51062. if (this._streaming) {
  51063. this._htmlAudioElement.playbackRate = this._playbackRate;
  51064. }
  51065. else {
  51066. if (this._soundSource) {
  51067. this._soundSource.playbackRate.value = this._playbackRate;
  51068. }
  51069. }
  51070. }
  51071. }
  51072. };
  51073. Sound.prototype._createSpatialParameters = function () {
  51074. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  51075. if (this._scene.headphone) {
  51076. this._panningModel = "HRTF";
  51077. }
  51078. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  51079. this._updateSpatialParameters();
  51080. this._soundPanner.connect(this._ouputAudioNode);
  51081. this._inputAudioNode = this._soundPanner;
  51082. }
  51083. };
  51084. Sound.prototype._updateSpatialParameters = function () {
  51085. if (this.spatialSound && this._soundPanner) {
  51086. if (this.useCustomAttenuation) {
  51087. // Tricks to disable in a way embedded Web Audio attenuation
  51088. this._soundPanner.distanceModel = "linear";
  51089. this._soundPanner.maxDistance = Number.MAX_VALUE;
  51090. this._soundPanner.refDistance = 1;
  51091. this._soundPanner.rolloffFactor = 1;
  51092. this._soundPanner.panningModel = this._panningModel;
  51093. }
  51094. else {
  51095. this._soundPanner.distanceModel = this.distanceModel;
  51096. this._soundPanner.maxDistance = this.maxDistance;
  51097. this._soundPanner.refDistance = this.refDistance;
  51098. this._soundPanner.rolloffFactor = this.rolloffFactor;
  51099. this._soundPanner.panningModel = this._panningModel;
  51100. }
  51101. }
  51102. };
  51103. Sound.prototype.switchPanningModelToHRTF = function () {
  51104. this._panningModel = "HRTF";
  51105. this._switchPanningModel();
  51106. };
  51107. Sound.prototype.switchPanningModelToEqualPower = function () {
  51108. this._panningModel = "equalpower";
  51109. this._switchPanningModel();
  51110. };
  51111. Sound.prototype._switchPanningModel = function () {
  51112. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  51113. this._soundPanner.panningModel = this._panningModel;
  51114. }
  51115. };
  51116. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  51117. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51118. if (this._isOutputConnected) {
  51119. this._ouputAudioNode.disconnect();
  51120. }
  51121. this._ouputAudioNode.connect(soundTrackAudioNode);
  51122. this._isOutputConnected = true;
  51123. }
  51124. };
  51125. /**
  51126. * Transform this sound into a directional source
  51127. * @param coneInnerAngle Size of the inner cone in degree
  51128. * @param coneOuterAngle Size of the outer cone in degree
  51129. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  51130. */
  51131. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  51132. if (coneOuterAngle < coneInnerAngle) {
  51133. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  51134. return;
  51135. }
  51136. this._coneInnerAngle = coneInnerAngle;
  51137. this._coneOuterAngle = coneOuterAngle;
  51138. this._coneOuterGain = coneOuterGain;
  51139. this._isDirectional = true;
  51140. if (this.isPlaying && this.loop) {
  51141. this.stop();
  51142. this.play();
  51143. }
  51144. };
  51145. Sound.prototype.setPosition = function (newPosition) {
  51146. this._position = newPosition;
  51147. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  51148. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  51149. }
  51150. };
  51151. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  51152. this._localDirection = newLocalDirection;
  51153. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  51154. this._updateDirection();
  51155. }
  51156. };
  51157. Sound.prototype._updateDirection = function () {
  51158. if (!this._connectedMesh || !this._soundPanner) {
  51159. return;
  51160. }
  51161. var mat = this._connectedMesh.getWorldMatrix();
  51162. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  51163. direction.normalize();
  51164. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  51165. };
  51166. Sound.prototype.updateDistanceFromListener = function () {
  51167. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  51168. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  51169. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  51170. }
  51171. };
  51172. Sound.prototype.setAttenuationFunction = function (callback) {
  51173. this._customAttenuationFunction = callback;
  51174. };
  51175. /**
  51176. * Play the sound
  51177. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  51178. * @param offset (optional) Start the sound setting it at a specific time
  51179. */
  51180. Sound.prototype.play = function (time, offset) {
  51181. var _this = this;
  51182. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  51183. try {
  51184. if (this._startOffset < 0) {
  51185. time = -this._startOffset;
  51186. this._startOffset = 0;
  51187. }
  51188. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  51189. if (!this._soundSource || !this._streamingSource) {
  51190. if (this.spatialSound && this._soundPanner) {
  51191. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  51192. if (this._isDirectional) {
  51193. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  51194. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  51195. this._soundPanner.coneOuterGain = this._coneOuterGain;
  51196. if (this._connectedMesh) {
  51197. this._updateDirection();
  51198. }
  51199. else {
  51200. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  51201. }
  51202. }
  51203. }
  51204. }
  51205. if (this._streaming) {
  51206. if (!this._streamingSource) {
  51207. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  51208. this._htmlAudioElement.onended = function () { _this._onended(); };
  51209. this._htmlAudioElement.playbackRate = this._playbackRate;
  51210. }
  51211. this._streamingSource.disconnect();
  51212. this._streamingSource.connect(this._inputAudioNode);
  51213. this._htmlAudioElement.play();
  51214. }
  51215. else {
  51216. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  51217. this._soundSource.buffer = this._audioBuffer;
  51218. this._soundSource.connect(this._inputAudioNode);
  51219. this._soundSource.loop = this.loop;
  51220. this._soundSource.playbackRate.value = this._playbackRate;
  51221. this._soundSource.onended = function () { _this._onended(); };
  51222. if (this._soundSource.buffer) {
  51223. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  51224. }
  51225. }
  51226. this._startTime = startTime;
  51227. this.isPlaying = true;
  51228. this.isPaused = false;
  51229. }
  51230. catch (ex) {
  51231. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  51232. }
  51233. }
  51234. };
  51235. Sound.prototype._onended = function () {
  51236. this.isPlaying = false;
  51237. if (this.onended) {
  51238. this.onended();
  51239. }
  51240. };
  51241. /**
  51242. * Stop the sound
  51243. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  51244. */
  51245. Sound.prototype.stop = function (time) {
  51246. if (this.isPlaying) {
  51247. if (this._streaming) {
  51248. this._htmlAudioElement.pause();
  51249. // Test needed for Firefox or it will generate an Invalid State Error
  51250. if (this._htmlAudioElement.currentTime > 0) {
  51251. this._htmlAudioElement.currentTime = 0;
  51252. }
  51253. }
  51254. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  51255. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  51256. this._soundSource.stop(stopTime);
  51257. this._soundSource.onended = function () { };
  51258. if (!this.isPaused) {
  51259. this._startOffset = 0;
  51260. }
  51261. }
  51262. this.isPlaying = false;
  51263. }
  51264. };
  51265. Sound.prototype.pause = function () {
  51266. if (this.isPlaying) {
  51267. this.isPaused = true;
  51268. if (this._streaming) {
  51269. this._htmlAudioElement.pause();
  51270. }
  51271. else if (BABYLON.Engine.audioEngine.audioContext) {
  51272. this.stop(0);
  51273. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  51274. }
  51275. }
  51276. };
  51277. Sound.prototype.setVolume = function (newVolume, time) {
  51278. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  51279. if (time && BABYLON.Engine.audioEngine.audioContext) {
  51280. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  51281. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  51282. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  51283. }
  51284. else {
  51285. this._soundGain.gain.value = newVolume;
  51286. }
  51287. }
  51288. this._volume = newVolume;
  51289. };
  51290. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  51291. this._playbackRate = newPlaybackRate;
  51292. if (this.isPlaying) {
  51293. if (this._streaming) {
  51294. this._htmlAudioElement.playbackRate = this._playbackRate;
  51295. }
  51296. else if (this._soundSource) {
  51297. this._soundSource.playbackRate.value = this._playbackRate;
  51298. }
  51299. }
  51300. };
  51301. Sound.prototype.getVolume = function () {
  51302. return this._volume;
  51303. };
  51304. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  51305. var _this = this;
  51306. if (this._connectedMesh && this._registerFunc) {
  51307. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  51308. this._registerFunc = null;
  51309. }
  51310. this._connectedMesh = meshToConnectTo;
  51311. if (!this.spatialSound) {
  51312. this.spatialSound = true;
  51313. this._createSpatialParameters();
  51314. if (this.isPlaying && this.loop) {
  51315. this.stop();
  51316. this.play();
  51317. }
  51318. }
  51319. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  51320. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  51321. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  51322. };
  51323. Sound.prototype.detachFromMesh = function () {
  51324. if (this._connectedMesh && this._registerFunc) {
  51325. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  51326. this._registerFunc = null;
  51327. this._connectedMesh = null;
  51328. }
  51329. };
  51330. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  51331. if (!node.getBoundingInfo) {
  51332. return;
  51333. }
  51334. var mesh = node;
  51335. var boundingInfo = mesh.getBoundingInfo();
  51336. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  51337. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  51338. this._updateDirection();
  51339. }
  51340. };
  51341. Sound.prototype.clone = function () {
  51342. var _this = this;
  51343. if (!this._streaming) {
  51344. var setBufferAndRun = function () {
  51345. if (_this._isReadyToPlay) {
  51346. clonedSound._audioBuffer = _this.getAudioBuffer();
  51347. clonedSound._isReadyToPlay = true;
  51348. if (clonedSound.autoplay) {
  51349. clonedSound.play();
  51350. }
  51351. }
  51352. else {
  51353. window.setTimeout(setBufferAndRun, 300);
  51354. }
  51355. };
  51356. var currentOptions = {
  51357. autoplay: this.autoplay, loop: this.loop,
  51358. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  51359. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  51360. refDistance: this.refDistance, distanceModel: this.distanceModel
  51361. };
  51362. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  51363. if (this.useCustomAttenuation) {
  51364. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  51365. }
  51366. clonedSound.setPosition(this._position);
  51367. clonedSound.setPlaybackRate(this._playbackRate);
  51368. setBufferAndRun();
  51369. return clonedSound;
  51370. }
  51371. else {
  51372. return null;
  51373. }
  51374. };
  51375. Sound.prototype.getAudioBuffer = function () {
  51376. return this._audioBuffer;
  51377. };
  51378. Sound.prototype.serialize = function () {
  51379. var serializationObject = {
  51380. name: this.name,
  51381. url: this.name,
  51382. autoplay: this.autoplay,
  51383. loop: this.loop,
  51384. volume: this._volume,
  51385. spatialSound: this.spatialSound,
  51386. maxDistance: this.maxDistance,
  51387. rolloffFactor: this.rolloffFactor,
  51388. refDistance: this.refDistance,
  51389. distanceModel: this.distanceModel,
  51390. playbackRate: this._playbackRate,
  51391. panningModel: this._panningModel,
  51392. soundTrackId: this.soundTrackId
  51393. };
  51394. if (this.spatialSound) {
  51395. if (this._connectedMesh)
  51396. serializationObject.connectedMeshId = this._connectedMesh.id;
  51397. serializationObject.position = this._position.asArray();
  51398. serializationObject.refDistance = this.refDistance;
  51399. serializationObject.distanceModel = this.distanceModel;
  51400. serializationObject.isDirectional = this._isDirectional;
  51401. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  51402. serializationObject.coneInnerAngle = this._coneInnerAngle;
  51403. serializationObject.coneOuterAngle = this._coneOuterAngle;
  51404. serializationObject.coneOuterGain = this._coneOuterGain;
  51405. }
  51406. return serializationObject;
  51407. };
  51408. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  51409. var soundName = parsedSound.name;
  51410. var soundUrl;
  51411. if (parsedSound.url) {
  51412. soundUrl = rootUrl + parsedSound.url;
  51413. }
  51414. else {
  51415. soundUrl = rootUrl + soundName;
  51416. }
  51417. var options = {
  51418. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  51419. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  51420. rolloffFactor: parsedSound.rolloffFactor,
  51421. refDistance: parsedSound.refDistance,
  51422. distanceModel: parsedSound.distanceModel,
  51423. playbackRate: parsedSound.playbackRate
  51424. };
  51425. var newSound;
  51426. if (!sourceSound) {
  51427. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  51428. scene._addPendingData(newSound);
  51429. }
  51430. else {
  51431. var setBufferAndRun = function () {
  51432. if (sourceSound._isReadyToPlay) {
  51433. newSound._audioBuffer = sourceSound.getAudioBuffer();
  51434. newSound._isReadyToPlay = true;
  51435. if (newSound.autoplay) {
  51436. newSound.play();
  51437. }
  51438. }
  51439. else {
  51440. window.setTimeout(setBufferAndRun, 300);
  51441. }
  51442. };
  51443. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  51444. setBufferAndRun();
  51445. }
  51446. if (parsedSound.position) {
  51447. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  51448. newSound.setPosition(soundPosition);
  51449. }
  51450. if (parsedSound.isDirectional) {
  51451. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  51452. if (parsedSound.localDirectionToMesh) {
  51453. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  51454. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  51455. }
  51456. }
  51457. if (parsedSound.connectedMeshId) {
  51458. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  51459. if (connectedMesh) {
  51460. newSound.attachToMesh(connectedMesh);
  51461. }
  51462. }
  51463. return newSound;
  51464. };
  51465. return Sound;
  51466. }());
  51467. BABYLON.Sound = Sound;
  51468. })(BABYLON || (BABYLON = {}));
  51469. //# sourceMappingURL=babylon.sound.js.map
  51470. var BABYLON;
  51471. (function (BABYLON) {
  51472. var SoundTrack = /** @class */ (function () {
  51473. function SoundTrack(scene, options) {
  51474. this.id = -1;
  51475. this._isMainTrack = false;
  51476. this._isInitialized = false;
  51477. this._scene = scene;
  51478. this.soundCollection = new Array();
  51479. this._options = options;
  51480. if (!this._isMainTrack) {
  51481. this._scene.soundTracks.push(this);
  51482. this.id = this._scene.soundTracks.length - 1;
  51483. }
  51484. }
  51485. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  51486. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  51487. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  51488. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  51489. if (this._options) {
  51490. if (this._options.volume) {
  51491. this._outputAudioNode.gain.value = this._options.volume;
  51492. }
  51493. if (this._options.mainTrack) {
  51494. this._isMainTrack = this._options.mainTrack;
  51495. }
  51496. }
  51497. this._isInitialized = true;
  51498. }
  51499. };
  51500. SoundTrack.prototype.dispose = function () {
  51501. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51502. if (this._connectedAnalyser) {
  51503. this._connectedAnalyser.stopDebugCanvas();
  51504. }
  51505. while (this.soundCollection.length) {
  51506. this.soundCollection[0].dispose();
  51507. }
  51508. if (this._outputAudioNode) {
  51509. this._outputAudioNode.disconnect();
  51510. }
  51511. this._outputAudioNode = null;
  51512. }
  51513. };
  51514. SoundTrack.prototype.AddSound = function (sound) {
  51515. if (!this._isInitialized) {
  51516. this._initializeSoundTrackAudioGraph();
  51517. }
  51518. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51519. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  51520. }
  51521. if (sound.soundTrackId) {
  51522. if (sound.soundTrackId === -1) {
  51523. this._scene.mainSoundTrack.RemoveSound(sound);
  51524. }
  51525. else {
  51526. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  51527. }
  51528. }
  51529. this.soundCollection.push(sound);
  51530. sound.soundTrackId = this.id;
  51531. };
  51532. SoundTrack.prototype.RemoveSound = function (sound) {
  51533. var index = this.soundCollection.indexOf(sound);
  51534. if (index !== -1) {
  51535. this.soundCollection.splice(index, 1);
  51536. }
  51537. };
  51538. SoundTrack.prototype.setVolume = function (newVolume) {
  51539. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51540. this._outputAudioNode.gain.value = newVolume;
  51541. }
  51542. };
  51543. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  51544. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51545. for (var i = 0; i < this.soundCollection.length; i++) {
  51546. this.soundCollection[i].switchPanningModelToHRTF();
  51547. }
  51548. }
  51549. };
  51550. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  51551. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51552. for (var i = 0; i < this.soundCollection.length; i++) {
  51553. this.soundCollection[i].switchPanningModelToEqualPower();
  51554. }
  51555. }
  51556. };
  51557. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  51558. if (this._connectedAnalyser) {
  51559. this._connectedAnalyser.stopDebugCanvas();
  51560. }
  51561. this._connectedAnalyser = analyser;
  51562. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51563. this._outputAudioNode.disconnect();
  51564. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  51565. }
  51566. };
  51567. return SoundTrack;
  51568. }());
  51569. BABYLON.SoundTrack = SoundTrack;
  51570. })(BABYLON || (BABYLON = {}));
  51571. //# sourceMappingURL=babylon.soundtrack.js.map
  51572. var BABYLON;
  51573. (function (BABYLON) {
  51574. var Analyser = /** @class */ (function () {
  51575. function Analyser(scene) {
  51576. this.SMOOTHING = 0.75;
  51577. this.FFT_SIZE = 512;
  51578. this.BARGRAPHAMPLITUDE = 256;
  51579. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  51580. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  51581. this._scene = scene;
  51582. this._audioEngine = BABYLON.Engine.audioEngine;
  51583. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  51584. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  51585. this._webAudioAnalyser.minDecibels = -140;
  51586. this._webAudioAnalyser.maxDecibels = 0;
  51587. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51588. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51589. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  51590. }
  51591. }
  51592. Analyser.prototype.getFrequencyBinCount = function () {
  51593. if (this._audioEngine.canUseWebAudio) {
  51594. return this._webAudioAnalyser.frequencyBinCount;
  51595. }
  51596. else {
  51597. return 0;
  51598. }
  51599. };
  51600. Analyser.prototype.getByteFrequencyData = function () {
  51601. if (this._audioEngine.canUseWebAudio) {
  51602. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51603. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51604. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  51605. }
  51606. return this._byteFreqs;
  51607. };
  51608. Analyser.prototype.getByteTimeDomainData = function () {
  51609. if (this._audioEngine.canUseWebAudio) {
  51610. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51611. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51612. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  51613. }
  51614. return this._byteTime;
  51615. };
  51616. Analyser.prototype.getFloatFrequencyData = function () {
  51617. if (this._audioEngine.canUseWebAudio) {
  51618. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51619. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51620. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  51621. }
  51622. return this._floatFreqs;
  51623. };
  51624. Analyser.prototype.drawDebugCanvas = function () {
  51625. var _this = this;
  51626. if (this._audioEngine.canUseWebAudio) {
  51627. if (!this._debugCanvas) {
  51628. this._debugCanvas = document.createElement("canvas");
  51629. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  51630. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  51631. this._debugCanvas.style.position = "absolute";
  51632. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  51633. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  51634. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  51635. document.body.appendChild(this._debugCanvas);
  51636. this._registerFunc = function () {
  51637. _this.drawDebugCanvas();
  51638. };
  51639. this._scene.registerBeforeRender(this._registerFunc);
  51640. }
  51641. if (this._registerFunc && this._debugCanvasContext) {
  51642. var workingArray = this.getByteFrequencyData();
  51643. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  51644. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  51645. // Draw the frequency domain chart.
  51646. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  51647. var value = workingArray[i];
  51648. var percent = value / this.BARGRAPHAMPLITUDE;
  51649. var height = this.DEBUGCANVASSIZE.height * percent;
  51650. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  51651. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  51652. var hue = i / this.getFrequencyBinCount() * 360;
  51653. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  51654. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  51655. }
  51656. }
  51657. }
  51658. };
  51659. Analyser.prototype.stopDebugCanvas = function () {
  51660. if (this._debugCanvas) {
  51661. if (this._registerFunc) {
  51662. this._scene.unregisterBeforeRender(this._registerFunc);
  51663. this._registerFunc = null;
  51664. }
  51665. document.body.removeChild(this._debugCanvas);
  51666. this._debugCanvas = null;
  51667. this._debugCanvasContext = null;
  51668. }
  51669. };
  51670. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  51671. if (this._audioEngine.canUseWebAudio) {
  51672. inputAudioNode.connect(this._webAudioAnalyser);
  51673. this._webAudioAnalyser.connect(outputAudioNode);
  51674. }
  51675. };
  51676. Analyser.prototype.dispose = function () {
  51677. if (this._audioEngine.canUseWebAudio) {
  51678. this._webAudioAnalyser.disconnect();
  51679. }
  51680. };
  51681. return Analyser;
  51682. }());
  51683. BABYLON.Analyser = Analyser;
  51684. })(BABYLON || (BABYLON = {}));
  51685. //# sourceMappingURL=babylon.analyser.js.map
  51686. var BABYLON;
  51687. (function (BABYLON) {
  51688. var CubeTexture = /** @class */ (function (_super) {
  51689. __extends(CubeTexture, _super);
  51690. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  51691. if (extensions === void 0) { extensions = null; }
  51692. if (noMipmap === void 0) { noMipmap = false; }
  51693. if (files === void 0) { files = null; }
  51694. if (onLoad === void 0) { onLoad = null; }
  51695. if (onError === void 0) { onError = null; }
  51696. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  51697. if (prefiltered === void 0) { prefiltered = false; }
  51698. if (forcedExtension === void 0) { forcedExtension = null; }
  51699. var _this = _super.call(this, scene) || this;
  51700. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51701. _this.name = rootUrl;
  51702. _this.url = rootUrl;
  51703. _this._noMipmap = noMipmap;
  51704. _this.hasAlpha = false;
  51705. _this._format = format;
  51706. _this._prefiltered = prefiltered;
  51707. _this.isCube = true;
  51708. _this._textureMatrix = BABYLON.Matrix.Identity();
  51709. if (prefiltered) {
  51710. _this.gammaSpace = false;
  51711. }
  51712. if (!rootUrl && !files) {
  51713. return _this;
  51714. }
  51715. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  51716. var lastDot = rootUrl.lastIndexOf(".");
  51717. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  51718. var isDDS = (extension === ".dds");
  51719. if (!files) {
  51720. if (!isDDS && !extensions) {
  51721. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  51722. }
  51723. files = [];
  51724. if (extensions) {
  51725. for (var index = 0; index < extensions.length; index++) {
  51726. files.push(rootUrl + extensions[index]);
  51727. }
  51728. }
  51729. }
  51730. _this._files = files;
  51731. if (!_this._texture) {
  51732. if (!scene.useDelayedTextureLoading) {
  51733. if (prefiltered) {
  51734. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  51735. }
  51736. else {
  51737. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  51738. }
  51739. }
  51740. else {
  51741. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51742. }
  51743. }
  51744. else if (onLoad) {
  51745. if (_this._texture.isReady) {
  51746. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  51747. }
  51748. else {
  51749. _this._texture.onLoadedObservable.add(onLoad);
  51750. }
  51751. }
  51752. return _this;
  51753. }
  51754. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  51755. return new CubeTexture("", scene, null, noMipmap, files);
  51756. };
  51757. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  51758. if (forcedExtension === void 0) { forcedExtension = null; }
  51759. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  51760. };
  51761. // Methods
  51762. CubeTexture.prototype.delayLoad = function () {
  51763. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51764. return;
  51765. }
  51766. var scene = this.getScene();
  51767. if (!scene) {
  51768. return;
  51769. }
  51770. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51771. this._texture = this._getFromCache(this.url, this._noMipmap);
  51772. if (!this._texture) {
  51773. if (this._prefiltered) {
  51774. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  51775. }
  51776. else {
  51777. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  51778. }
  51779. }
  51780. };
  51781. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  51782. return this._textureMatrix;
  51783. };
  51784. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  51785. this._textureMatrix = value;
  51786. };
  51787. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51788. var texture = BABYLON.SerializationHelper.Parse(function () {
  51789. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  51790. }, parsedTexture, scene);
  51791. // Animations
  51792. if (parsedTexture.animations) {
  51793. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  51794. var parsedAnimation = parsedTexture.animations[animationIndex];
  51795. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51796. }
  51797. }
  51798. return texture;
  51799. };
  51800. CubeTexture.prototype.clone = function () {
  51801. var _this = this;
  51802. return BABYLON.SerializationHelper.Clone(function () {
  51803. var scene = _this.getScene();
  51804. if (!scene) {
  51805. return _this;
  51806. }
  51807. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  51808. }, this);
  51809. };
  51810. return CubeTexture;
  51811. }(BABYLON.BaseTexture));
  51812. BABYLON.CubeTexture = CubeTexture;
  51813. })(BABYLON || (BABYLON = {}));
  51814. //# sourceMappingURL=babylon.cubeTexture.js.map
  51815. var BABYLON;
  51816. (function (BABYLON) {
  51817. var RenderTargetTexture = /** @class */ (function (_super) {
  51818. __extends(RenderTargetTexture, _super);
  51819. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  51820. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  51821. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51822. if (isCube === void 0) { isCube = false; }
  51823. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51824. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  51825. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  51826. if (isMulti === void 0) { isMulti = false; }
  51827. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  51828. _this.isCube = isCube;
  51829. /**
  51830. * Use this list to define the list of mesh you want to render.
  51831. */
  51832. _this.renderList = new Array();
  51833. _this.renderParticles = true;
  51834. _this.renderSprites = false;
  51835. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  51836. _this.ignoreCameraViewport = false;
  51837. // Events
  51838. /**
  51839. * An event triggered when the texture is unbind.
  51840. * @type {BABYLON.Observable}
  51841. */
  51842. _this.onBeforeBindObservable = new BABYLON.Observable();
  51843. /**
  51844. * An event triggered when the texture is unbind.
  51845. * @type {BABYLON.Observable}
  51846. */
  51847. _this.onAfterUnbindObservable = new BABYLON.Observable();
  51848. /**
  51849. * An event triggered before rendering the texture
  51850. * @type {BABYLON.Observable}
  51851. */
  51852. _this.onBeforeRenderObservable = new BABYLON.Observable();
  51853. /**
  51854. * An event triggered after rendering the texture
  51855. * @type {BABYLON.Observable}
  51856. */
  51857. _this.onAfterRenderObservable = new BABYLON.Observable();
  51858. /**
  51859. * An event triggered after the texture clear
  51860. * @type {BABYLON.Observable}
  51861. */
  51862. _this.onClearObservable = new BABYLON.Observable();
  51863. _this._currentRefreshId = -1;
  51864. _this._refreshRate = 1;
  51865. _this._samples = 1;
  51866. scene = _this.getScene();
  51867. if (!scene) {
  51868. return _this;
  51869. }
  51870. _this._engine = scene.getEngine();
  51871. _this.name = name;
  51872. _this.isRenderTarget = true;
  51873. _this._initialSizeParameter = size;
  51874. _this._processSizeParameter(size);
  51875. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  51876. });
  51877. _this._generateMipMaps = generateMipMaps ? true : false;
  51878. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  51879. // Rendering groups
  51880. _this._renderingManager = new BABYLON.RenderingManager(scene);
  51881. if (isMulti) {
  51882. return _this;
  51883. }
  51884. _this._renderTargetOptions = {
  51885. generateMipMaps: generateMipMaps,
  51886. type: type,
  51887. samplingMode: samplingMode,
  51888. generateDepthBuffer: generateDepthBuffer,
  51889. generateStencilBuffer: generateStencilBuffer
  51890. };
  51891. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  51892. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51893. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51894. }
  51895. if (isCube) {
  51896. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  51897. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  51898. _this._textureMatrix = BABYLON.Matrix.Identity();
  51899. }
  51900. else {
  51901. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  51902. }
  51903. return _this;
  51904. }
  51905. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  51906. get: function () {
  51907. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  51908. },
  51909. enumerable: true,
  51910. configurable: true
  51911. });
  51912. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  51913. get: function () {
  51914. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  51915. },
  51916. enumerable: true,
  51917. configurable: true
  51918. });
  51919. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  51920. get: function () {
  51921. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  51922. },
  51923. enumerable: true,
  51924. configurable: true
  51925. });
  51926. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  51927. set: function (callback) {
  51928. if (this._onAfterUnbindObserver) {
  51929. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  51930. }
  51931. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  51932. },
  51933. enumerable: true,
  51934. configurable: true
  51935. });
  51936. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  51937. set: function (callback) {
  51938. if (this._onBeforeRenderObserver) {
  51939. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  51940. }
  51941. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  51942. },
  51943. enumerable: true,
  51944. configurable: true
  51945. });
  51946. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  51947. set: function (callback) {
  51948. if (this._onAfterRenderObserver) {
  51949. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  51950. }
  51951. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  51952. },
  51953. enumerable: true,
  51954. configurable: true
  51955. });
  51956. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  51957. set: function (callback) {
  51958. if (this._onClearObserver) {
  51959. this.onClearObservable.remove(this._onClearObserver);
  51960. }
  51961. this._onClearObserver = this.onClearObservable.add(callback);
  51962. },
  51963. enumerable: true,
  51964. configurable: true
  51965. });
  51966. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  51967. get: function () {
  51968. return this._renderTargetOptions;
  51969. },
  51970. enumerable: true,
  51971. configurable: true
  51972. });
  51973. RenderTargetTexture.prototype._onRatioRescale = function () {
  51974. if (this._sizeRatio) {
  51975. this.resize(this._initialSizeParameter);
  51976. }
  51977. };
  51978. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  51979. if (size.ratio) {
  51980. this._sizeRatio = size.ratio;
  51981. this._size = {
  51982. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  51983. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  51984. };
  51985. }
  51986. else {
  51987. this._size = size;
  51988. }
  51989. };
  51990. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  51991. get: function () {
  51992. return this._samples;
  51993. },
  51994. set: function (value) {
  51995. if (this._samples === value) {
  51996. return;
  51997. }
  51998. var scene = this.getScene();
  51999. if (!scene) {
  52000. return;
  52001. }
  52002. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  52003. },
  52004. enumerable: true,
  52005. configurable: true
  52006. });
  52007. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  52008. this._currentRefreshId = -1;
  52009. };
  52010. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  52011. get: function () {
  52012. return this._refreshRate;
  52013. },
  52014. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  52015. set: function (value) {
  52016. this._refreshRate = value;
  52017. this.resetRefreshCounter();
  52018. },
  52019. enumerable: true,
  52020. configurable: true
  52021. });
  52022. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  52023. if (!this._postProcessManager) {
  52024. var scene = this.getScene();
  52025. if (!scene) {
  52026. return;
  52027. }
  52028. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  52029. this._postProcesses = new Array();
  52030. }
  52031. this._postProcesses.push(postProcess);
  52032. this._postProcesses[0].autoClear = false;
  52033. };
  52034. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  52035. if (!this._postProcesses) {
  52036. return;
  52037. }
  52038. if (dispose) {
  52039. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  52040. var postProcess = _a[_i];
  52041. postProcess.dispose();
  52042. }
  52043. }
  52044. this._postProcesses = [];
  52045. };
  52046. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  52047. if (!this._postProcesses) {
  52048. return;
  52049. }
  52050. var index = this._postProcesses.indexOf(postProcess);
  52051. if (index === -1) {
  52052. return;
  52053. }
  52054. this._postProcesses.splice(index, 1);
  52055. if (this._postProcesses.length > 0) {
  52056. this._postProcesses[0].autoClear = false;
  52057. }
  52058. };
  52059. RenderTargetTexture.prototype._shouldRender = function () {
  52060. if (this._currentRefreshId === -1) {
  52061. this._currentRefreshId = 1;
  52062. return true;
  52063. }
  52064. if (this.refreshRate === this._currentRefreshId) {
  52065. this._currentRefreshId = 1;
  52066. return true;
  52067. }
  52068. this._currentRefreshId++;
  52069. return false;
  52070. };
  52071. RenderTargetTexture.prototype.getRenderSize = function () {
  52072. if (this._size.width) {
  52073. return this._size.width;
  52074. }
  52075. return this._size;
  52076. };
  52077. RenderTargetTexture.prototype.getRenderWidth = function () {
  52078. if (this._size.width) {
  52079. return this._size.width;
  52080. }
  52081. return this._size;
  52082. };
  52083. RenderTargetTexture.prototype.getRenderHeight = function () {
  52084. if (this._size.width) {
  52085. return this._size.height;
  52086. }
  52087. return this._size;
  52088. };
  52089. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  52090. get: function () {
  52091. return true;
  52092. },
  52093. enumerable: true,
  52094. configurable: true
  52095. });
  52096. RenderTargetTexture.prototype.scale = function (ratio) {
  52097. var newSize = this.getRenderSize() * ratio;
  52098. this.resize(newSize);
  52099. };
  52100. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  52101. if (this.isCube) {
  52102. return this._textureMatrix;
  52103. }
  52104. return _super.prototype.getReflectionTextureMatrix.call(this);
  52105. };
  52106. RenderTargetTexture.prototype.resize = function (size) {
  52107. this.releaseInternalTexture();
  52108. var scene = this.getScene();
  52109. if (!scene) {
  52110. return;
  52111. }
  52112. this._processSizeParameter(size);
  52113. if (this.isCube) {
  52114. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  52115. }
  52116. else {
  52117. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  52118. }
  52119. };
  52120. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  52121. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  52122. if (dumpForDebug === void 0) { dumpForDebug = false; }
  52123. var scene = this.getScene();
  52124. if (!scene) {
  52125. return;
  52126. }
  52127. var engine = scene.getEngine();
  52128. if (this.useCameraPostProcesses !== undefined) {
  52129. useCameraPostProcess = this.useCameraPostProcesses;
  52130. }
  52131. if (this._waitingRenderList) {
  52132. this.renderList = [];
  52133. for (var index = 0; index < this._waitingRenderList.length; index++) {
  52134. var id = this._waitingRenderList[index];
  52135. var mesh_1 = scene.getMeshByID(id);
  52136. if (mesh_1) {
  52137. this.renderList.push(mesh_1);
  52138. }
  52139. }
  52140. delete this._waitingRenderList;
  52141. }
  52142. // Is predicate defined?
  52143. if (this.renderListPredicate) {
  52144. if (this.renderList) {
  52145. this.renderList.splice(0); // Clear previous renderList
  52146. }
  52147. else {
  52148. this.renderList = [];
  52149. }
  52150. var scene = this.getScene();
  52151. if (!scene) {
  52152. return;
  52153. }
  52154. var sceneMeshes = scene.meshes;
  52155. for (var index = 0; index < sceneMeshes.length; index++) {
  52156. var mesh = sceneMeshes[index];
  52157. if (this.renderListPredicate(mesh)) {
  52158. this.renderList.push(mesh);
  52159. }
  52160. }
  52161. }
  52162. this.onBeforeBindObservable.notifyObservers(this);
  52163. // Set custom projection.
  52164. // Needs to be before binding to prevent changing the aspect ratio.
  52165. var camera;
  52166. if (this.activeCamera) {
  52167. camera = this.activeCamera;
  52168. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  52169. if (this.activeCamera !== scene.activeCamera) {
  52170. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  52171. }
  52172. }
  52173. else {
  52174. camera = scene.activeCamera;
  52175. if (camera) {
  52176. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  52177. }
  52178. }
  52179. // Prepare renderingManager
  52180. this._renderingManager.reset();
  52181. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  52182. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  52183. var sceneRenderId = scene.getRenderId();
  52184. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  52185. var mesh = currentRenderList[meshIndex];
  52186. if (mesh) {
  52187. if (!mesh.isReady()) {
  52188. // Reset _currentRefreshId
  52189. this.resetRefreshCounter();
  52190. continue;
  52191. }
  52192. mesh._preActivateForIntermediateRendering(sceneRenderId);
  52193. var isMasked = void 0;
  52194. if (!this.renderList && camera) {
  52195. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  52196. }
  52197. else {
  52198. isMasked = false;
  52199. }
  52200. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  52201. mesh._activate(sceneRenderId);
  52202. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  52203. var subMesh = mesh.subMeshes[subIndex];
  52204. scene._activeIndices.addCount(subMesh.indexCount, false);
  52205. this._renderingManager.dispatch(subMesh, mesh);
  52206. }
  52207. }
  52208. }
  52209. }
  52210. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  52211. var particleSystem = scene.particleSystems[particleIndex];
  52212. var emitter = particleSystem.emitter;
  52213. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  52214. continue;
  52215. }
  52216. if (currentRenderList.indexOf(emitter) >= 0) {
  52217. this._renderingManager.dispatchParticles(particleSystem);
  52218. }
  52219. }
  52220. if (this.isCube) {
  52221. for (var face = 0; face < 6; face++) {
  52222. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  52223. scene.incrementRenderId();
  52224. scene.resetCachedMaterial();
  52225. }
  52226. }
  52227. else {
  52228. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  52229. }
  52230. this.onAfterUnbindObservable.notifyObservers(this);
  52231. if (scene.activeCamera) {
  52232. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  52233. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  52234. }
  52235. engine.setViewport(scene.activeCamera.viewport);
  52236. }
  52237. scene.resetCachedMaterial();
  52238. };
  52239. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  52240. var minimum = 128;
  52241. var x = renderDimension * scale;
  52242. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  52243. // Ensure we don't exceed the render dimension (while staying POT)
  52244. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  52245. };
  52246. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  52247. var _this = this;
  52248. if (!this._texture) {
  52249. return;
  52250. }
  52251. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  52252. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  52253. });
  52254. };
  52255. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  52256. var scene = this.getScene();
  52257. if (!scene) {
  52258. return;
  52259. }
  52260. var engine = scene.getEngine();
  52261. if (!this._texture) {
  52262. return;
  52263. }
  52264. // Bind
  52265. if (this._postProcessManager) {
  52266. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  52267. }
  52268. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  52269. if (this._texture) {
  52270. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  52271. }
  52272. }
  52273. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  52274. // Clear
  52275. if (this.onClearObservable.hasObservers()) {
  52276. this.onClearObservable.notifyObservers(engine);
  52277. }
  52278. else {
  52279. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  52280. }
  52281. if (!this._doNotChangeAspectRatio) {
  52282. scene.updateTransformMatrix(true);
  52283. }
  52284. // Render
  52285. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  52286. if (this._postProcessManager) {
  52287. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  52288. }
  52289. else if (useCameraPostProcess) {
  52290. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  52291. }
  52292. if (!this._doNotChangeAspectRatio) {
  52293. scene.updateTransformMatrix(true);
  52294. }
  52295. // Dump ?
  52296. if (dumpForDebug) {
  52297. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  52298. }
  52299. // Unbind
  52300. if (!this.isCube || faceIndex === 5) {
  52301. if (this.isCube) {
  52302. if (faceIndex === 5) {
  52303. engine.generateMipMapsForCubemap(this._texture);
  52304. }
  52305. }
  52306. this.unbindFrameBuffer(engine, faceIndex);
  52307. }
  52308. else {
  52309. this.onAfterRenderObservable.notifyObservers(faceIndex);
  52310. }
  52311. };
  52312. /**
  52313. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  52314. * This allowed control for front to back rendering or reversly depending of the special needs.
  52315. *
  52316. * @param renderingGroupId The rendering group id corresponding to its index
  52317. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  52318. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  52319. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  52320. */
  52321. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  52322. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  52323. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  52324. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  52325. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  52326. };
  52327. /**
  52328. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  52329. *
  52330. * @param renderingGroupId The rendering group id corresponding to its index
  52331. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  52332. */
  52333. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  52334. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  52335. };
  52336. RenderTargetTexture.prototype.clone = function () {
  52337. var textureSize = this.getSize();
  52338. 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);
  52339. // Base texture
  52340. newTexture.hasAlpha = this.hasAlpha;
  52341. newTexture.level = this.level;
  52342. // RenderTarget Texture
  52343. newTexture.coordinatesMode = this.coordinatesMode;
  52344. if (this.renderList) {
  52345. newTexture.renderList = this.renderList.slice(0);
  52346. }
  52347. return newTexture;
  52348. };
  52349. RenderTargetTexture.prototype.serialize = function () {
  52350. if (!this.name) {
  52351. return null;
  52352. }
  52353. var serializationObject = _super.prototype.serialize.call(this);
  52354. serializationObject.renderTargetSize = this.getRenderSize();
  52355. serializationObject.renderList = [];
  52356. if (this.renderList) {
  52357. for (var index = 0; index < this.renderList.length; index++) {
  52358. serializationObject.renderList.push(this.renderList[index].id);
  52359. }
  52360. }
  52361. return serializationObject;
  52362. };
  52363. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  52364. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  52365. var objBuffer = this.getInternalTexture();
  52366. var scene = this.getScene();
  52367. if (objBuffer && scene) {
  52368. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  52369. }
  52370. };
  52371. RenderTargetTexture.prototype.dispose = function () {
  52372. if (this._postProcessManager) {
  52373. this._postProcessManager.dispose();
  52374. this._postProcessManager = null;
  52375. }
  52376. this.clearPostProcesses(true);
  52377. if (this._resizeObserver) {
  52378. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  52379. this._resizeObserver = null;
  52380. }
  52381. this.renderList = null;
  52382. // Remove from custom render targets
  52383. var scene = this.getScene();
  52384. if (!scene) {
  52385. return;
  52386. }
  52387. var index = scene.customRenderTargets.indexOf(this);
  52388. if (index >= 0) {
  52389. scene.customRenderTargets.splice(index, 1);
  52390. }
  52391. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  52392. var camera = _a[_i];
  52393. index = camera.customRenderTargets.indexOf(this);
  52394. if (index >= 0) {
  52395. camera.customRenderTargets.splice(index, 1);
  52396. }
  52397. }
  52398. _super.prototype.dispose.call(this);
  52399. };
  52400. RenderTargetTexture.prototype._rebuild = function () {
  52401. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  52402. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  52403. }
  52404. if (this._postProcessManager) {
  52405. this._postProcessManager._rebuild();
  52406. }
  52407. };
  52408. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  52409. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  52410. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  52411. return RenderTargetTexture;
  52412. }(BABYLON.Texture));
  52413. BABYLON.RenderTargetTexture = RenderTargetTexture;
  52414. })(BABYLON || (BABYLON = {}));
  52415. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  52416. var BABYLON;
  52417. (function (BABYLON) {
  52418. ;
  52419. var MultiRenderTarget = /** @class */ (function (_super) {
  52420. __extends(MultiRenderTarget, _super);
  52421. function MultiRenderTarget(name, size, count, scene, options) {
  52422. var _this = this;
  52423. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  52424. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  52425. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  52426. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  52427. _this._engine = scene.getEngine();
  52428. if (!_this.isSupported) {
  52429. _this.dispose();
  52430. return;
  52431. }
  52432. var types = [];
  52433. var samplingModes = [];
  52434. for (var i = 0; i < count; i++) {
  52435. if (options && options.types && options.types[i] !== undefined) {
  52436. types.push(options.types[i]);
  52437. }
  52438. else {
  52439. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52440. }
  52441. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  52442. samplingModes.push(options.samplingModes[i]);
  52443. }
  52444. else {
  52445. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52446. }
  52447. }
  52448. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  52449. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  52450. _this._size = size;
  52451. _this._multiRenderTargetOptions = {
  52452. samplingModes: samplingModes,
  52453. generateMipMaps: generateMipMaps,
  52454. generateDepthBuffer: generateDepthBuffer,
  52455. generateStencilBuffer: generateStencilBuffer,
  52456. generateDepthTexture: generateDepthTexture,
  52457. types: types,
  52458. textureCount: count
  52459. };
  52460. _this._createInternalTextures();
  52461. _this._createTextures();
  52462. return _this;
  52463. }
  52464. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  52465. get: function () {
  52466. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  52467. },
  52468. enumerable: true,
  52469. configurable: true
  52470. });
  52471. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  52472. get: function () {
  52473. return this._textures;
  52474. },
  52475. enumerable: true,
  52476. configurable: true
  52477. });
  52478. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  52479. get: function () {
  52480. return this._textures[this._textures.length - 1];
  52481. },
  52482. enumerable: true,
  52483. configurable: true
  52484. });
  52485. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  52486. set: function (wrap) {
  52487. if (this._textures) {
  52488. for (var i = 0; i < this._textures.length; i++) {
  52489. this._textures[i].wrapU = wrap;
  52490. }
  52491. }
  52492. },
  52493. enumerable: true,
  52494. configurable: true
  52495. });
  52496. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  52497. set: function (wrap) {
  52498. if (this._textures) {
  52499. for (var i = 0; i < this._textures.length; i++) {
  52500. this._textures[i].wrapV = wrap;
  52501. }
  52502. }
  52503. },
  52504. enumerable: true,
  52505. configurable: true
  52506. });
  52507. MultiRenderTarget.prototype._rebuild = function () {
  52508. this.releaseInternalTextures();
  52509. this._createInternalTextures();
  52510. for (var i = 0; i < this._internalTextures.length; i++) {
  52511. var texture = this._textures[i];
  52512. texture._texture = this._internalTextures[i];
  52513. }
  52514. // Keeps references to frame buffer and stencil/depth buffer
  52515. this._texture = this._internalTextures[0];
  52516. };
  52517. MultiRenderTarget.prototype._createInternalTextures = function () {
  52518. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  52519. };
  52520. MultiRenderTarget.prototype._createTextures = function () {
  52521. this._textures = [];
  52522. for (var i = 0; i < this._internalTextures.length; i++) {
  52523. var texture = new BABYLON.Texture(null, this.getScene());
  52524. texture._texture = this._internalTextures[i];
  52525. this._textures.push(texture);
  52526. }
  52527. // Keeps references to frame buffer and stencil/depth buffer
  52528. this._texture = this._internalTextures[0];
  52529. };
  52530. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  52531. get: function () {
  52532. return this._samples;
  52533. },
  52534. set: function (value) {
  52535. if (this._samples === value) {
  52536. return;
  52537. }
  52538. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  52539. },
  52540. enumerable: true,
  52541. configurable: true
  52542. });
  52543. MultiRenderTarget.prototype.resize = function (size) {
  52544. this.releaseInternalTextures();
  52545. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  52546. this._createInternalTextures();
  52547. };
  52548. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  52549. var _this = this;
  52550. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  52551. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  52552. });
  52553. };
  52554. MultiRenderTarget.prototype.dispose = function () {
  52555. this.releaseInternalTextures();
  52556. _super.prototype.dispose.call(this);
  52557. };
  52558. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  52559. if (!this._internalTextures) {
  52560. return;
  52561. }
  52562. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  52563. if (this._internalTextures[i] !== undefined) {
  52564. this._internalTextures[i].dispose();
  52565. this._internalTextures.splice(i, 1);
  52566. }
  52567. }
  52568. };
  52569. return MultiRenderTarget;
  52570. }(BABYLON.RenderTargetTexture));
  52571. BABYLON.MultiRenderTarget = MultiRenderTarget;
  52572. })(BABYLON || (BABYLON = {}));
  52573. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  52574. var BABYLON;
  52575. (function (BABYLON) {
  52576. var MirrorTexture = /** @class */ (function (_super) {
  52577. __extends(MirrorTexture, _super);
  52578. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  52579. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52580. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52581. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  52582. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  52583. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  52584. _this._transformMatrix = BABYLON.Matrix.Zero();
  52585. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  52586. _this._adaptiveBlurKernel = 0;
  52587. _this._blurKernelX = 0;
  52588. _this._blurKernelY = 0;
  52589. _this._blurRatio = 1.0;
  52590. _this.ignoreCameraViewport = true;
  52591. _this.onBeforeRenderObservable.add(function () {
  52592. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  52593. _this._savedViewMatrix = scene.getViewMatrix();
  52594. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  52595. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  52596. scene.clipPlane = _this.mirrorPlane;
  52597. scene.getEngine().cullBackFaces = false;
  52598. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  52599. });
  52600. _this.onAfterRenderObservable.add(function () {
  52601. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  52602. scene.getEngine().cullBackFaces = true;
  52603. scene._mirroredCameraPosition = null;
  52604. delete scene.clipPlane;
  52605. });
  52606. return _this;
  52607. }
  52608. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  52609. get: function () {
  52610. return this._blurRatio;
  52611. },
  52612. set: function (value) {
  52613. if (this._blurRatio === value) {
  52614. return;
  52615. }
  52616. this._blurRatio = value;
  52617. this._preparePostProcesses();
  52618. },
  52619. enumerable: true,
  52620. configurable: true
  52621. });
  52622. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  52623. set: function (value) {
  52624. this._adaptiveBlurKernel = value;
  52625. this._autoComputeBlurKernel();
  52626. },
  52627. enumerable: true,
  52628. configurable: true
  52629. });
  52630. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  52631. set: function (value) {
  52632. this.blurKernelX = value;
  52633. this.blurKernelY = value;
  52634. },
  52635. enumerable: true,
  52636. configurable: true
  52637. });
  52638. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  52639. get: function () {
  52640. return this._blurKernelX;
  52641. },
  52642. set: function (value) {
  52643. if (this._blurKernelX === value) {
  52644. return;
  52645. }
  52646. this._blurKernelX = value;
  52647. this._preparePostProcesses();
  52648. },
  52649. enumerable: true,
  52650. configurable: true
  52651. });
  52652. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  52653. get: function () {
  52654. return this._blurKernelY;
  52655. },
  52656. set: function (value) {
  52657. if (this._blurKernelY === value) {
  52658. return;
  52659. }
  52660. this._blurKernelY = value;
  52661. this._preparePostProcesses();
  52662. },
  52663. enumerable: true,
  52664. configurable: true
  52665. });
  52666. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  52667. var engine = this.getScene().getEngine();
  52668. var dw = this.getRenderWidth() / engine.getRenderWidth();
  52669. var dh = this.getRenderHeight() / engine.getRenderHeight();
  52670. this.blurKernelX = this._adaptiveBlurKernel * dw;
  52671. this.blurKernelY = this._adaptiveBlurKernel * dh;
  52672. };
  52673. MirrorTexture.prototype._onRatioRescale = function () {
  52674. if (this._sizeRatio) {
  52675. this.resize(this._initialSizeParameter);
  52676. if (!this._adaptiveBlurKernel) {
  52677. this._preparePostProcesses();
  52678. }
  52679. }
  52680. if (this._adaptiveBlurKernel) {
  52681. this._autoComputeBlurKernel();
  52682. }
  52683. };
  52684. MirrorTexture.prototype._preparePostProcesses = function () {
  52685. this.clearPostProcesses(true);
  52686. if (this._blurKernelX && this._blurKernelY) {
  52687. var engine = this.getScene().getEngine();
  52688. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52689. 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);
  52690. this._blurX.autoClear = false;
  52691. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  52692. this._blurX.outputTexture = this._texture;
  52693. }
  52694. else {
  52695. this._blurX.alwaysForcePOT = true;
  52696. }
  52697. 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);
  52698. this._blurY.autoClear = false;
  52699. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  52700. this.addPostProcess(this._blurX);
  52701. this.addPostProcess(this._blurY);
  52702. }
  52703. else {
  52704. if (this._blurY) {
  52705. this.removePostProcess(this._blurY);
  52706. this._blurY.dispose();
  52707. this._blurY = null;
  52708. }
  52709. if (this._blurX) {
  52710. this.removePostProcess(this._blurX);
  52711. this._blurX.dispose();
  52712. this._blurX = null;
  52713. }
  52714. }
  52715. };
  52716. MirrorTexture.prototype.clone = function () {
  52717. var scene = this.getScene();
  52718. if (!scene) {
  52719. return this;
  52720. }
  52721. var textureSize = this.getSize();
  52722. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  52723. // Base texture
  52724. newTexture.hasAlpha = this.hasAlpha;
  52725. newTexture.level = this.level;
  52726. // Mirror Texture
  52727. newTexture.mirrorPlane = this.mirrorPlane.clone();
  52728. if (this.renderList) {
  52729. newTexture.renderList = this.renderList.slice(0);
  52730. }
  52731. return newTexture;
  52732. };
  52733. MirrorTexture.prototype.serialize = function () {
  52734. if (!this.name) {
  52735. return null;
  52736. }
  52737. var serializationObject = _super.prototype.serialize.call(this);
  52738. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  52739. return serializationObject;
  52740. };
  52741. return MirrorTexture;
  52742. }(BABYLON.RenderTargetTexture));
  52743. BABYLON.MirrorTexture = MirrorTexture;
  52744. })(BABYLON || (BABYLON = {}));
  52745. //# sourceMappingURL=babylon.mirrorTexture.js.map
  52746. var BABYLON;
  52747. (function (BABYLON) {
  52748. /**
  52749. * Creates a refraction texture used by refraction channel of the standard material.
  52750. * @param name the texture name
  52751. * @param size size of the underlying texture
  52752. * @param scene root scene
  52753. */
  52754. var RefractionTexture = /** @class */ (function (_super) {
  52755. __extends(RefractionTexture, _super);
  52756. function RefractionTexture(name, size, scene, generateMipMaps) {
  52757. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  52758. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  52759. _this.depth = 2.0;
  52760. _this.onBeforeRenderObservable.add(function () {
  52761. scene.clipPlane = _this.refractionPlane;
  52762. });
  52763. _this.onAfterRenderObservable.add(function () {
  52764. delete scene.clipPlane;
  52765. });
  52766. return _this;
  52767. }
  52768. RefractionTexture.prototype.clone = function () {
  52769. var scene = this.getScene();
  52770. if (!scene) {
  52771. return this;
  52772. }
  52773. var textureSize = this.getSize();
  52774. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  52775. // Base texture
  52776. newTexture.hasAlpha = this.hasAlpha;
  52777. newTexture.level = this.level;
  52778. // Refraction Texture
  52779. newTexture.refractionPlane = this.refractionPlane.clone();
  52780. if (this.renderList) {
  52781. newTexture.renderList = this.renderList.slice(0);
  52782. }
  52783. newTexture.depth = this.depth;
  52784. return newTexture;
  52785. };
  52786. RefractionTexture.prototype.serialize = function () {
  52787. if (!this.name) {
  52788. return null;
  52789. }
  52790. var serializationObject = _super.prototype.serialize.call(this);
  52791. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  52792. serializationObject.depth = this.depth;
  52793. return serializationObject;
  52794. };
  52795. return RefractionTexture;
  52796. }(BABYLON.RenderTargetTexture));
  52797. BABYLON.RefractionTexture = RefractionTexture;
  52798. })(BABYLON || (BABYLON = {}));
  52799. //# sourceMappingURL=babylon.refractionTexture.js.map
  52800. var BABYLON;
  52801. (function (BABYLON) {
  52802. var DynamicTexture = /** @class */ (function (_super) {
  52803. __extends(DynamicTexture, _super);
  52804. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  52805. if (scene === void 0) { scene = null; }
  52806. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52807. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  52808. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  52809. _this.name = name;
  52810. _this._engine = _this.getScene().getEngine();
  52811. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52812. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52813. _this._generateMipMaps = generateMipMaps;
  52814. if (options.getContext) {
  52815. _this._canvas = options;
  52816. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52817. }
  52818. else {
  52819. _this._canvas = document.createElement("canvas");
  52820. if (options.width) {
  52821. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52822. }
  52823. else {
  52824. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  52825. }
  52826. }
  52827. var textureSize = _this.getSize();
  52828. _this._canvas.width = textureSize.width;
  52829. _this._canvas.height = textureSize.height;
  52830. _this._context = _this._canvas.getContext("2d");
  52831. return _this;
  52832. }
  52833. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  52834. get: function () {
  52835. return true;
  52836. },
  52837. enumerable: true,
  52838. configurable: true
  52839. });
  52840. DynamicTexture.prototype._recreate = function (textureSize) {
  52841. this._canvas.width = textureSize.width;
  52842. this._canvas.height = textureSize.height;
  52843. this.releaseInternalTexture();
  52844. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  52845. };
  52846. DynamicTexture.prototype.scale = function (ratio) {
  52847. var textureSize = this.getSize();
  52848. textureSize.width *= ratio;
  52849. textureSize.height *= ratio;
  52850. this._recreate(textureSize);
  52851. };
  52852. DynamicTexture.prototype.scaleTo = function (width, height) {
  52853. var textureSize = this.getSize();
  52854. textureSize.width = width;
  52855. textureSize.height = height;
  52856. this._recreate(textureSize);
  52857. };
  52858. DynamicTexture.prototype.getContext = function () {
  52859. return this._context;
  52860. };
  52861. DynamicTexture.prototype.clear = function () {
  52862. var size = this.getSize();
  52863. this._context.fillRect(0, 0, size.width, size.height);
  52864. };
  52865. DynamicTexture.prototype.update = function (invertY) {
  52866. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  52867. };
  52868. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  52869. if (update === void 0) { update = true; }
  52870. var size = this.getSize();
  52871. if (clearColor) {
  52872. this._context.fillStyle = clearColor;
  52873. this._context.fillRect(0, 0, size.width, size.height);
  52874. }
  52875. this._context.font = font;
  52876. if (x === null || x === undefined) {
  52877. var textSize = this._context.measureText(text);
  52878. x = (size.width - textSize.width) / 2;
  52879. }
  52880. if (y === null || y === undefined) {
  52881. var fontSize = parseInt((font.replace(/\D/g, '')));
  52882. ;
  52883. y = (size.height / 2) + (fontSize / 3.65);
  52884. }
  52885. this._context.fillStyle = color;
  52886. this._context.fillText(text, x, y);
  52887. if (update) {
  52888. this.update(invertY);
  52889. }
  52890. };
  52891. DynamicTexture.prototype.clone = function () {
  52892. var scene = this.getScene();
  52893. if (!scene) {
  52894. return this;
  52895. }
  52896. var textureSize = this.getSize();
  52897. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  52898. // Base texture
  52899. newTexture.hasAlpha = this.hasAlpha;
  52900. newTexture.level = this.level;
  52901. // Dynamic Texture
  52902. newTexture.wrapU = this.wrapU;
  52903. newTexture.wrapV = this.wrapV;
  52904. return newTexture;
  52905. };
  52906. DynamicTexture.prototype._rebuild = function () {
  52907. this.update();
  52908. };
  52909. return DynamicTexture;
  52910. }(BABYLON.Texture));
  52911. BABYLON.DynamicTexture = DynamicTexture;
  52912. })(BABYLON || (BABYLON = {}));
  52913. //# sourceMappingURL=babylon.dynamicTexture.js.map
  52914. var BABYLON;
  52915. (function (BABYLON) {
  52916. var VideoTexture = /** @class */ (function (_super) {
  52917. __extends(VideoTexture, _super);
  52918. /**
  52919. * Creates a video texture.
  52920. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  52921. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  52922. * @param {BABYLON.Scene} scene is obviously the current scene.
  52923. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  52924. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  52925. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  52926. */
  52927. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  52928. if (generateMipMaps === void 0) { generateMipMaps = false; }
  52929. if (invertY === void 0) { invertY = false; }
  52930. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52931. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  52932. _this._autoLaunch = true;
  52933. var urls = null;
  52934. _this.name = name;
  52935. if (urlsOrVideo instanceof HTMLVideoElement) {
  52936. _this.video = urlsOrVideo;
  52937. }
  52938. else {
  52939. urls = urlsOrVideo;
  52940. _this.video = document.createElement("video");
  52941. _this.video.autoplay = false;
  52942. _this.video.loop = true;
  52943. BABYLON.Tools.SetCorsBehavior(urls, _this.video);
  52944. }
  52945. _this._engine = _this.getScene().getEngine();
  52946. _this._generateMipMaps = generateMipMaps;
  52947. _this._samplingMode = samplingMode;
  52948. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  52949. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52950. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52951. }
  52952. else {
  52953. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52954. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52955. _this._generateMipMaps = false;
  52956. }
  52957. if (urls) {
  52958. _this.video.addEventListener("canplay", function () {
  52959. if (_this._texture === undefined) {
  52960. _this._createTexture();
  52961. }
  52962. });
  52963. urls.forEach(function (url) {
  52964. var source = document.createElement("source");
  52965. source.src = url;
  52966. _this.video.appendChild(source);
  52967. });
  52968. }
  52969. else {
  52970. _this._createTexture();
  52971. }
  52972. _this._lastUpdate = BABYLON.Tools.Now;
  52973. return _this;
  52974. }
  52975. VideoTexture.prototype.__setTextureReady = function () {
  52976. if (this._texture) {
  52977. this._texture.isReady = true;
  52978. }
  52979. };
  52980. VideoTexture.prototype._createTexture = function () {
  52981. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  52982. if (this._autoLaunch) {
  52983. this._autoLaunch = false;
  52984. this.video.play();
  52985. }
  52986. this._setTextureReady = this.__setTextureReady.bind(this);
  52987. this.video.addEventListener("playing", this._setTextureReady);
  52988. };
  52989. VideoTexture.prototype._rebuild = function () {
  52990. this.update();
  52991. };
  52992. VideoTexture.prototype.update = function () {
  52993. var now = BABYLON.Tools.Now;
  52994. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  52995. return false;
  52996. }
  52997. this._lastUpdate = now;
  52998. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  52999. return true;
  53000. };
  53001. VideoTexture.prototype.dispose = function () {
  53002. _super.prototype.dispose.call(this);
  53003. this.video.removeEventListener("playing", this._setTextureReady);
  53004. };
  53005. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  53006. var video = document.createElement("video");
  53007. var constraintsDeviceId;
  53008. if (constraints && constraints.deviceId) {
  53009. constraintsDeviceId = {
  53010. exact: constraints.deviceId
  53011. };
  53012. }
  53013. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  53014. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  53015. if (navigator.getUserMedia) {
  53016. navigator.getUserMedia({
  53017. video: {
  53018. deviceId: constraintsDeviceId,
  53019. width: {
  53020. min: (constraints && constraints.minWidth) || 256,
  53021. max: (constraints && constraints.maxWidth) || 640
  53022. },
  53023. height: {
  53024. min: (constraints && constraints.minHeight) || 256,
  53025. max: (constraints && constraints.maxHeight) || 480
  53026. }
  53027. }
  53028. }, function (stream) {
  53029. if (video.mozSrcObject !== undefined) {
  53030. video.mozSrcObject = stream;
  53031. }
  53032. else {
  53033. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  53034. }
  53035. video.play();
  53036. if (onReady) {
  53037. onReady(new VideoTexture("video", video, scene, true, true));
  53038. }
  53039. }, function (e) {
  53040. BABYLON.Tools.Error(e.name);
  53041. });
  53042. }
  53043. };
  53044. return VideoTexture;
  53045. }(BABYLON.Texture));
  53046. BABYLON.VideoTexture = VideoTexture;
  53047. })(BABYLON || (BABYLON = {}));
  53048. //# sourceMappingURL=babylon.videoTexture.js.map
  53049. var BABYLON;
  53050. (function (BABYLON) {
  53051. var RawTexture = /** @class */ (function (_super) {
  53052. __extends(RawTexture, _super);
  53053. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  53054. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53055. if (invertY === void 0) { invertY = false; }
  53056. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53057. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53058. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  53059. _this.format = format;
  53060. _this._engine = scene.getEngine();
  53061. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  53062. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53063. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53064. return _this;
  53065. }
  53066. RawTexture.prototype.update = function (data) {
  53067. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  53068. };
  53069. // Statics
  53070. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53071. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53072. if (invertY === void 0) { invertY = false; }
  53073. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53074. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  53075. };
  53076. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53077. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53078. if (invertY === void 0) { invertY = false; }
  53079. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53080. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  53081. };
  53082. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53083. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53084. if (invertY === void 0) { invertY = false; }
  53085. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53086. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  53087. };
  53088. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  53089. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53090. if (invertY === void 0) { invertY = false; }
  53091. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53092. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53093. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  53094. };
  53095. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  53096. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53097. if (invertY === void 0) { invertY = false; }
  53098. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53099. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53100. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  53101. };
  53102. return RawTexture;
  53103. }(BABYLON.Texture));
  53104. BABYLON.RawTexture = RawTexture;
  53105. })(BABYLON || (BABYLON = {}));
  53106. //# sourceMappingURL=babylon.rawTexture.js.map
  53107. var BABYLON;
  53108. (function (BABYLON) {
  53109. var PostProcess = /** @class */ (function () {
  53110. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  53111. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  53112. if (defines === void 0) { defines = null; }
  53113. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53114. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  53115. if (blockCompilation === void 0) { blockCompilation = false; }
  53116. this.name = name;
  53117. this.width = -1;
  53118. this.height = -1;
  53119. this.autoClear = true;
  53120. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  53121. this.animations = new Array();
  53122. /*
  53123. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  53124. Can only be used on a single postprocess or on the last one of a chain.
  53125. */
  53126. this.enablePixelPerfectMode = false;
  53127. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  53128. this.alwaysForcePOT = false;
  53129. this.samples = 1;
  53130. this.adaptScaleToCurrentViewport = false;
  53131. this._reusable = false;
  53132. this._textures = new BABYLON.SmartArray(2);
  53133. this._currentRenderTextureInd = 0;
  53134. this._scaleRatio = new BABYLON.Vector2(1, 1);
  53135. this._texelSize = BABYLON.Vector2.Zero();
  53136. // Events
  53137. /**
  53138. * An event triggered when the postprocess is activated.
  53139. * @type {BABYLON.Observable}
  53140. */
  53141. this.onActivateObservable = new BABYLON.Observable();
  53142. /**
  53143. * An event triggered when the postprocess changes its size.
  53144. * @type {BABYLON.Observable}
  53145. */
  53146. this.onSizeChangedObservable = new BABYLON.Observable();
  53147. /**
  53148. * An event triggered when the postprocess applies its effect.
  53149. * @type {BABYLON.Observable}
  53150. */
  53151. this.onApplyObservable = new BABYLON.Observable();
  53152. /**
  53153. * An event triggered before rendering the postprocess
  53154. * @type {BABYLON.Observable}
  53155. */
  53156. this.onBeforeRenderObservable = new BABYLON.Observable();
  53157. /**
  53158. * An event triggered after rendering the postprocess
  53159. * @type {BABYLON.Observable}
  53160. */
  53161. this.onAfterRenderObservable = new BABYLON.Observable();
  53162. if (camera != null) {
  53163. this._camera = camera;
  53164. this._scene = camera.getScene();
  53165. camera.attachPostProcess(this);
  53166. this._engine = this._scene.getEngine();
  53167. this._scene.postProcesses.push(this);
  53168. }
  53169. else if (engine) {
  53170. this._engine = engine;
  53171. this._engine.postProcesses.push(this);
  53172. }
  53173. this._options = options;
  53174. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  53175. this._reusable = reusable || false;
  53176. this._textureType = textureType;
  53177. this._samplers = samplers || [];
  53178. this._samplers.push("textureSampler");
  53179. this._fragmentUrl = fragmentUrl;
  53180. this._vertexUrl = vertexUrl;
  53181. this._parameters = parameters || [];
  53182. this._parameters.push("scale");
  53183. this._indexParameters = indexParameters;
  53184. if (!blockCompilation) {
  53185. this.updateEffect(defines);
  53186. }
  53187. }
  53188. Object.defineProperty(PostProcess.prototype, "onActivate", {
  53189. set: function (callback) {
  53190. if (this._onActivateObserver) {
  53191. this.onActivateObservable.remove(this._onActivateObserver);
  53192. }
  53193. if (callback) {
  53194. this._onActivateObserver = this.onActivateObservable.add(callback);
  53195. }
  53196. },
  53197. enumerable: true,
  53198. configurable: true
  53199. });
  53200. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  53201. set: function (callback) {
  53202. if (this._onSizeChangedObserver) {
  53203. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  53204. }
  53205. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  53206. },
  53207. enumerable: true,
  53208. configurable: true
  53209. });
  53210. Object.defineProperty(PostProcess.prototype, "onApply", {
  53211. set: function (callback) {
  53212. if (this._onApplyObserver) {
  53213. this.onApplyObservable.remove(this._onApplyObserver);
  53214. }
  53215. this._onApplyObserver = this.onApplyObservable.add(callback);
  53216. },
  53217. enumerable: true,
  53218. configurable: true
  53219. });
  53220. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  53221. set: function (callback) {
  53222. if (this._onBeforeRenderObserver) {
  53223. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  53224. }
  53225. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  53226. },
  53227. enumerable: true,
  53228. configurable: true
  53229. });
  53230. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  53231. set: function (callback) {
  53232. if (this._onAfterRenderObserver) {
  53233. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  53234. }
  53235. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  53236. },
  53237. enumerable: true,
  53238. configurable: true
  53239. });
  53240. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  53241. get: function () {
  53242. return this._textures.data[this._currentRenderTextureInd];
  53243. },
  53244. set: function (value) {
  53245. this._forcedOutputTexture = value;
  53246. },
  53247. enumerable: true,
  53248. configurable: true
  53249. });
  53250. PostProcess.prototype.getCamera = function () {
  53251. return this._camera;
  53252. };
  53253. Object.defineProperty(PostProcess.prototype, "texelSize", {
  53254. get: function () {
  53255. if (this._shareOutputWithPostProcess) {
  53256. return this._shareOutputWithPostProcess.texelSize;
  53257. }
  53258. if (this._forcedOutputTexture) {
  53259. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  53260. }
  53261. return this._texelSize;
  53262. },
  53263. enumerable: true,
  53264. configurable: true
  53265. });
  53266. PostProcess.prototype.getEngine = function () {
  53267. return this._engine;
  53268. };
  53269. PostProcess.prototype.getEffect = function () {
  53270. return this._effect;
  53271. };
  53272. PostProcess.prototype.shareOutputWith = function (postProcess) {
  53273. this._disposeTextures();
  53274. this._shareOutputWithPostProcess = postProcess;
  53275. return this;
  53276. };
  53277. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  53278. if (defines === void 0) { defines = null; }
  53279. if (uniforms === void 0) { uniforms = null; }
  53280. if (samplers === void 0) { samplers = null; }
  53281. 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);
  53282. };
  53283. PostProcess.prototype.isReusable = function () {
  53284. return this._reusable;
  53285. };
  53286. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  53287. PostProcess.prototype.markTextureDirty = function () {
  53288. this.width = -1;
  53289. };
  53290. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  53291. var _this = this;
  53292. if (sourceTexture === void 0) { sourceTexture = null; }
  53293. camera = camera || this._camera;
  53294. var scene = camera.getScene();
  53295. var engine = scene.getEngine();
  53296. var maxSize = engine.getCaps().maxTextureSize;
  53297. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  53298. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  53299. var desiredWidth = (this._options.width || requiredWidth);
  53300. var desiredHeight = this._options.height || requiredHeight;
  53301. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  53302. if (this.adaptScaleToCurrentViewport) {
  53303. var currentViewport = engine.currentViewport;
  53304. if (currentViewport) {
  53305. desiredWidth *= currentViewport.width;
  53306. desiredHeight *= currentViewport.height;
  53307. }
  53308. }
  53309. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  53310. if (!this._options.width) {
  53311. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  53312. }
  53313. if (!this._options.height) {
  53314. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  53315. }
  53316. }
  53317. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  53318. if (this._textures.length > 0) {
  53319. for (var i = 0; i < this._textures.length; i++) {
  53320. this._engine._releaseTexture(this._textures.data[i]);
  53321. }
  53322. this._textures.reset();
  53323. }
  53324. this.width = desiredWidth;
  53325. this.height = desiredHeight;
  53326. var textureSize = { width: this.width, height: this.height };
  53327. var textureOptions = {
  53328. generateMipMaps: false,
  53329. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  53330. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  53331. samplingMode: this.renderTargetSamplingMode,
  53332. type: this._textureType
  53333. };
  53334. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  53335. if (this._reusable) {
  53336. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  53337. }
  53338. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  53339. this.onSizeChangedObservable.notifyObservers(this);
  53340. }
  53341. this._textures.forEach(function (texture) {
  53342. if (texture.samples !== _this.samples) {
  53343. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  53344. }
  53345. });
  53346. }
  53347. var target;
  53348. if (this._shareOutputWithPostProcess) {
  53349. target = this._shareOutputWithPostProcess.outputTexture;
  53350. }
  53351. else if (this._forcedOutputTexture) {
  53352. target = this._forcedOutputTexture;
  53353. this.width = this._forcedOutputTexture.width;
  53354. this.height = this._forcedOutputTexture.height;
  53355. }
  53356. else {
  53357. target = this.outputTexture;
  53358. }
  53359. if (this.enablePixelPerfectMode) {
  53360. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  53361. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  53362. }
  53363. else {
  53364. this._scaleRatio.copyFromFloats(1, 1);
  53365. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  53366. }
  53367. this.onActivateObservable.notifyObservers(camera);
  53368. // Clear
  53369. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  53370. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  53371. }
  53372. if (this._reusable) {
  53373. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  53374. }
  53375. };
  53376. Object.defineProperty(PostProcess.prototype, "isSupported", {
  53377. get: function () {
  53378. return this._effect.isSupported;
  53379. },
  53380. enumerable: true,
  53381. configurable: true
  53382. });
  53383. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  53384. get: function () {
  53385. if (this._shareOutputWithPostProcess) {
  53386. return this._shareOutputWithPostProcess.aspectRatio;
  53387. }
  53388. if (this._forcedOutputTexture) {
  53389. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  53390. }
  53391. return this.width / this.height;
  53392. },
  53393. enumerable: true,
  53394. configurable: true
  53395. });
  53396. /**
  53397. * Get a value indicating if the post-process is ready to be used
  53398. * @returns true if the post-process is ready (shader is compiled)
  53399. */
  53400. PostProcess.prototype.isReady = function () {
  53401. return this._effect && this._effect.isReady();
  53402. };
  53403. PostProcess.prototype.apply = function () {
  53404. // Check
  53405. if (!this._effect || !this._effect.isReady())
  53406. return null;
  53407. // States
  53408. this._engine.enableEffect(this._effect);
  53409. this._engine.setState(false);
  53410. this._engine.setDepthBuffer(false);
  53411. this._engine.setDepthWrite(false);
  53412. // Alpha
  53413. this._engine.setAlphaMode(this.alphaMode);
  53414. if (this.alphaConstants) {
  53415. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  53416. }
  53417. // Texture
  53418. var source;
  53419. if (this._shareOutputWithPostProcess) {
  53420. source = this._shareOutputWithPostProcess.outputTexture;
  53421. }
  53422. else if (this._forcedOutputTexture) {
  53423. source = this._forcedOutputTexture;
  53424. }
  53425. else {
  53426. source = this.outputTexture;
  53427. }
  53428. this._effect._bindTexture("textureSampler", source);
  53429. // Parameters
  53430. this._effect.setVector2("scale", this._scaleRatio);
  53431. this.onApplyObservable.notifyObservers(this._effect);
  53432. return this._effect;
  53433. };
  53434. PostProcess.prototype._disposeTextures = function () {
  53435. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  53436. return;
  53437. }
  53438. if (this._textures.length > 0) {
  53439. for (var i = 0; i < this._textures.length; i++) {
  53440. this._engine._releaseTexture(this._textures.data[i]);
  53441. }
  53442. }
  53443. this._textures.dispose();
  53444. };
  53445. PostProcess.prototype.dispose = function (camera) {
  53446. camera = camera || this._camera;
  53447. this._disposeTextures();
  53448. if (this._scene) {
  53449. var index_1 = this._scene.postProcesses.indexOf(this);
  53450. if (index_1 !== -1) {
  53451. this._scene.postProcesses.splice(index_1, 1);
  53452. }
  53453. }
  53454. else {
  53455. var index_2 = this._engine.postProcesses.indexOf(this);
  53456. if (index_2 !== -1) {
  53457. this._engine.postProcesses.splice(index_2, 1);
  53458. }
  53459. }
  53460. if (!camera) {
  53461. return;
  53462. }
  53463. camera.detachPostProcess(this);
  53464. var index = camera._postProcesses.indexOf(this);
  53465. if (index === 0 && camera._postProcesses.length > 0) {
  53466. this._camera._postProcesses[0].markTextureDirty();
  53467. }
  53468. this.onActivateObservable.clear();
  53469. this.onAfterRenderObservable.clear();
  53470. this.onApplyObservable.clear();
  53471. this.onBeforeRenderObservable.clear();
  53472. this.onSizeChangedObservable.clear();
  53473. };
  53474. return PostProcess;
  53475. }());
  53476. BABYLON.PostProcess = PostProcess;
  53477. })(BABYLON || (BABYLON = {}));
  53478. //# sourceMappingURL=babylon.postProcess.js.map
  53479. var BABYLON;
  53480. (function (BABYLON) {
  53481. var PassPostProcess = /** @class */ (function (_super) {
  53482. __extends(PassPostProcess, _super);
  53483. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53484. if (camera === void 0) { camera = null; }
  53485. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53486. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  53487. }
  53488. return PassPostProcess;
  53489. }(BABYLON.PostProcess));
  53490. BABYLON.PassPostProcess = PassPostProcess;
  53491. })(BABYLON || (BABYLON = {}));
  53492. //# sourceMappingURL=babylon.passPostProcess.js.map
  53493. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53494. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53495. s = arguments[i];
  53496. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53497. t[p] = s[p];
  53498. }
  53499. return t;
  53500. };
  53501. var BABYLON;
  53502. (function (BABYLON) {
  53503. var ShadowGenerator = /** @class */ (function () {
  53504. /**
  53505. * Creates a ShadowGenerator object.
  53506. * A ShadowGenerator is the required tool to use the shadows.
  53507. * Each light casting shadows needs to use its own ShadowGenerator.
  53508. * Required parameters :
  53509. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  53510. * - `light`: the light object generating the shadows.
  53511. * - `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.
  53512. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  53513. */
  53514. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  53515. // Members
  53516. this._bias = 0.00005;
  53517. this._blurBoxOffset = 1;
  53518. this._blurScale = 2;
  53519. this._blurKernel = 1;
  53520. this._useKernelBlur = false;
  53521. this._filter = ShadowGenerator.FILTER_NONE;
  53522. this._darkness = 0;
  53523. this._transparencyShadow = false;
  53524. /**
  53525. * Controls the extent to which the shadows fade out at the edge of the frustum
  53526. * Used only by directionals and spots
  53527. */
  53528. this.frustumEdgeFalloff = 0;
  53529. this.forceBackFacesOnly = false;
  53530. this._lightDirection = BABYLON.Vector3.Zero();
  53531. this._viewMatrix = BABYLON.Matrix.Zero();
  53532. this._projectionMatrix = BABYLON.Matrix.Zero();
  53533. this._transformMatrix = BABYLON.Matrix.Zero();
  53534. this._currentFaceIndex = 0;
  53535. this._currentFaceIndexCache = 0;
  53536. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  53537. this._mapSize = mapSize;
  53538. this._light = light;
  53539. this._scene = light.getScene();
  53540. light._shadowGenerator = this;
  53541. // Texture type fallback from float to int if not supported.
  53542. var caps = this._scene.getEngine().getCaps();
  53543. if (!useFullFloatFirst) {
  53544. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  53545. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53546. }
  53547. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  53548. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53549. }
  53550. else {
  53551. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53552. }
  53553. }
  53554. else {
  53555. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  53556. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53557. }
  53558. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  53559. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53560. }
  53561. else {
  53562. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53563. }
  53564. }
  53565. this._initializeGenerator();
  53566. }
  53567. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  53568. // Static
  53569. get: function () {
  53570. return ShadowGenerator._FILTER_NONE;
  53571. },
  53572. enumerable: true,
  53573. configurable: true
  53574. });
  53575. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  53576. get: function () {
  53577. return ShadowGenerator._FILTER_POISSONSAMPLING;
  53578. },
  53579. enumerable: true,
  53580. configurable: true
  53581. });
  53582. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  53583. get: function () {
  53584. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  53585. },
  53586. enumerable: true,
  53587. configurable: true
  53588. });
  53589. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  53590. get: function () {
  53591. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  53592. },
  53593. enumerable: true,
  53594. configurable: true
  53595. });
  53596. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  53597. get: function () {
  53598. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53599. },
  53600. enumerable: true,
  53601. configurable: true
  53602. });
  53603. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  53604. get: function () {
  53605. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53606. },
  53607. enumerable: true,
  53608. configurable: true
  53609. });
  53610. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  53611. get: function () {
  53612. return this._bias;
  53613. },
  53614. set: function (bias) {
  53615. this._bias = bias;
  53616. },
  53617. enumerable: true,
  53618. configurable: true
  53619. });
  53620. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  53621. get: function () {
  53622. return this._blurBoxOffset;
  53623. },
  53624. set: function (value) {
  53625. if (this._blurBoxOffset === value) {
  53626. return;
  53627. }
  53628. this._blurBoxOffset = value;
  53629. this._disposeBlurPostProcesses();
  53630. },
  53631. enumerable: true,
  53632. configurable: true
  53633. });
  53634. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  53635. get: function () {
  53636. return this._blurScale;
  53637. },
  53638. set: function (value) {
  53639. if (this._blurScale === value) {
  53640. return;
  53641. }
  53642. this._blurScale = value;
  53643. this._disposeBlurPostProcesses();
  53644. },
  53645. enumerable: true,
  53646. configurable: true
  53647. });
  53648. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  53649. get: function () {
  53650. return this._blurKernel;
  53651. },
  53652. set: function (value) {
  53653. if (this._blurKernel === value) {
  53654. return;
  53655. }
  53656. this._blurKernel = value;
  53657. this._disposeBlurPostProcesses();
  53658. },
  53659. enumerable: true,
  53660. configurable: true
  53661. });
  53662. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  53663. get: function () {
  53664. return this._useKernelBlur;
  53665. },
  53666. set: function (value) {
  53667. if (this._useKernelBlur === value) {
  53668. return;
  53669. }
  53670. this._useKernelBlur = value;
  53671. this._disposeBlurPostProcesses();
  53672. },
  53673. enumerable: true,
  53674. configurable: true
  53675. });
  53676. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  53677. get: function () {
  53678. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  53679. },
  53680. set: function (value) {
  53681. this._depthScale = value;
  53682. },
  53683. enumerable: true,
  53684. configurable: true
  53685. });
  53686. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  53687. get: function () {
  53688. return this._filter;
  53689. },
  53690. set: function (value) {
  53691. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  53692. if (this._light.needCube()) {
  53693. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53694. this.useExponentialShadowMap = true;
  53695. return;
  53696. }
  53697. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53698. this.useCloseExponentialShadowMap = true;
  53699. return;
  53700. }
  53701. }
  53702. if (this._filter === value) {
  53703. return;
  53704. }
  53705. this._filter = value;
  53706. this._disposeBlurPostProcesses();
  53707. this._applyFilterValues();
  53708. this._light._markMeshesAsLightDirty();
  53709. },
  53710. enumerable: true,
  53711. configurable: true
  53712. });
  53713. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  53714. get: function () {
  53715. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  53716. },
  53717. set: function (value) {
  53718. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  53719. return;
  53720. }
  53721. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  53722. },
  53723. enumerable: true,
  53724. configurable: true
  53725. });
  53726. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  53727. get: function () {
  53728. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53729. return this.useExponentialShadowMap;
  53730. },
  53731. set: function (value) {
  53732. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53733. this.useExponentialShadowMap = value;
  53734. },
  53735. enumerable: true,
  53736. configurable: true
  53737. });
  53738. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  53739. get: function () {
  53740. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53741. return this.useBlurExponentialShadowMap;
  53742. },
  53743. set: function (value) {
  53744. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53745. this.useBlurExponentialShadowMap = value;
  53746. },
  53747. enumerable: true,
  53748. configurable: true
  53749. });
  53750. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  53751. get: function () {
  53752. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  53753. },
  53754. set: function (value) {
  53755. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  53756. return;
  53757. }
  53758. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53759. },
  53760. enumerable: true,
  53761. configurable: true
  53762. });
  53763. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  53764. get: function () {
  53765. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  53766. },
  53767. set: function (value) {
  53768. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53769. return;
  53770. }
  53771. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53772. },
  53773. enumerable: true,
  53774. configurable: true
  53775. });
  53776. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  53777. get: function () {
  53778. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53779. },
  53780. set: function (value) {
  53781. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  53782. return;
  53783. }
  53784. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53785. },
  53786. enumerable: true,
  53787. configurable: true
  53788. });
  53789. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  53790. get: function () {
  53791. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53792. },
  53793. set: function (value) {
  53794. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53795. return;
  53796. }
  53797. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53798. },
  53799. enumerable: true,
  53800. configurable: true
  53801. });
  53802. /**
  53803. * Returns the darkness value (float).
  53804. */
  53805. ShadowGenerator.prototype.getDarkness = function () {
  53806. return this._darkness;
  53807. };
  53808. /**
  53809. * Sets the ShadowGenerator darkness value (float <= 1.0).
  53810. * Returns the ShadowGenerator.
  53811. */
  53812. ShadowGenerator.prototype.setDarkness = function (darkness) {
  53813. if (darkness >= 1.0)
  53814. this._darkness = 1.0;
  53815. else if (darkness <= 0.0)
  53816. this._darkness = 0.0;
  53817. else
  53818. this._darkness = darkness;
  53819. return this;
  53820. };
  53821. /**
  53822. * Sets the ability to have transparent shadow (boolean).
  53823. * Returns the ShadowGenerator.
  53824. */
  53825. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  53826. this._transparencyShadow = hasShadow;
  53827. return this;
  53828. };
  53829. /**
  53830. * Returns a RenderTargetTexture object : the shadow map texture.
  53831. */
  53832. ShadowGenerator.prototype.getShadowMap = function () {
  53833. return this._shadowMap;
  53834. };
  53835. /**
  53836. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  53837. */
  53838. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  53839. if (this._shadowMap2) {
  53840. return this._shadowMap2;
  53841. }
  53842. return this._shadowMap;
  53843. };
  53844. /**
  53845. * Helper function to add a mesh and its descendants to the list of shadow casters
  53846. * @param mesh Mesh to add
  53847. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  53848. */
  53849. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  53850. if (includeDescendants === void 0) { includeDescendants = true; }
  53851. if (!this._shadowMap) {
  53852. return this;
  53853. }
  53854. if (!this._shadowMap.renderList) {
  53855. this._shadowMap.renderList = [];
  53856. }
  53857. this._shadowMap.renderList.push(mesh);
  53858. if (includeDescendants) {
  53859. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  53860. }
  53861. return this;
  53862. var _a;
  53863. };
  53864. /**
  53865. * Helper function to remove a mesh and its descendants from the list of shadow casters
  53866. * @param mesh Mesh to remove
  53867. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  53868. */
  53869. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  53870. if (includeDescendants === void 0) { includeDescendants = true; }
  53871. if (!this._shadowMap || !this._shadowMap.renderList) {
  53872. return this;
  53873. }
  53874. var index = this._shadowMap.renderList.indexOf(mesh);
  53875. if (index !== -1) {
  53876. this._shadowMap.renderList.splice(index, 1);
  53877. }
  53878. if (includeDescendants) {
  53879. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  53880. var child = _a[_i];
  53881. this.removeShadowCaster(child);
  53882. }
  53883. }
  53884. return this;
  53885. };
  53886. /**
  53887. * Returns the associated light object.
  53888. */
  53889. ShadowGenerator.prototype.getLight = function () {
  53890. return this._light;
  53891. };
  53892. ShadowGenerator.prototype._initializeGenerator = function () {
  53893. this._light._markMeshesAsLightDirty();
  53894. this._initializeShadowMap();
  53895. };
  53896. ShadowGenerator.prototype._initializeShadowMap = function () {
  53897. var _this = this;
  53898. // Render target
  53899. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  53900. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53901. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53902. this._shadowMap.anisotropicFilteringLevel = 1;
  53903. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53904. this._shadowMap.renderParticles = false;
  53905. this._shadowMap.ignoreCameraViewport = true;
  53906. // Record Face Index before render.
  53907. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  53908. _this._currentFaceIndex = faceIndex;
  53909. });
  53910. // Custom render function.
  53911. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  53912. // Blur if required afer render.
  53913. this._shadowMap.onAfterUnbindObservable.add(function () {
  53914. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  53915. return;
  53916. }
  53917. var shadowMap = _this.getShadowMapForRendering();
  53918. if (shadowMap) {
  53919. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  53920. }
  53921. });
  53922. // Clear according to the chosen filter.
  53923. this._shadowMap.onClearObservable.add(function (engine) {
  53924. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  53925. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  53926. }
  53927. else {
  53928. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  53929. }
  53930. });
  53931. };
  53932. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  53933. var _this = this;
  53934. var engine = this._scene.getEngine();
  53935. var targetSize = this._mapSize / this.blurScale;
  53936. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  53937. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  53938. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53939. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53940. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53941. }
  53942. if (this.useKernelBlur) {
  53943. 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);
  53944. this._kernelBlurXPostprocess.width = targetSize;
  53945. this._kernelBlurXPostprocess.height = targetSize;
  53946. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  53947. effect.setTexture("textureSampler", _this._shadowMap);
  53948. });
  53949. 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);
  53950. this._kernelBlurXPostprocess.autoClear = false;
  53951. this._kernelBlurYPostprocess.autoClear = false;
  53952. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53953. this._kernelBlurXPostprocess.packedFloat = true;
  53954. this._kernelBlurYPostprocess.packedFloat = true;
  53955. }
  53956. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  53957. }
  53958. else {
  53959. 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);
  53960. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  53961. effect.setFloat2("screenSize", targetSize, targetSize);
  53962. effect.setTexture("textureSampler", _this._shadowMap);
  53963. });
  53964. this._boxBlurPostprocess.autoClear = false;
  53965. this._blurPostProcesses = [this._boxBlurPostprocess];
  53966. }
  53967. };
  53968. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  53969. var index;
  53970. var engine = this._scene.getEngine();
  53971. if (depthOnlySubMeshes.length) {
  53972. engine.setColorWrite(false);
  53973. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  53974. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  53975. }
  53976. engine.setColorWrite(true);
  53977. }
  53978. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53979. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  53980. }
  53981. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53982. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  53983. }
  53984. if (this._transparencyShadow) {
  53985. for (index = 0; index < transparentSubMeshes.length; index++) {
  53986. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  53987. }
  53988. }
  53989. };
  53990. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  53991. var _this = this;
  53992. var mesh = subMesh.getRenderingMesh();
  53993. var scene = this._scene;
  53994. var engine = scene.getEngine();
  53995. var material = subMesh.getMaterial();
  53996. if (!material) {
  53997. return;
  53998. }
  53999. // Culling
  54000. engine.setState(material.backFaceCulling);
  54001. // Managing instances
  54002. var batch = mesh._getInstancesRenderList(subMesh._id);
  54003. if (batch.mustReturn) {
  54004. return;
  54005. }
  54006. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  54007. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  54008. engine.enableEffect(this._effect);
  54009. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  54010. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  54011. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  54012. this._effect.setVector3("lightPosition", this.getLight().position);
  54013. if (scene.activeCamera) {
  54014. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  54015. }
  54016. // Alpha test
  54017. if (material && material.needAlphaTesting()) {
  54018. var alphaTexture = material.getAlphaTestTexture();
  54019. if (alphaTexture) {
  54020. this._effect.setTexture("diffuseSampler", alphaTexture);
  54021. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  54022. }
  54023. }
  54024. // Bones
  54025. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54026. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  54027. }
  54028. if (this.forceBackFacesOnly) {
  54029. engine.setState(true, 0, false, true);
  54030. }
  54031. // Draw
  54032. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  54033. if (this.forceBackFacesOnly) {
  54034. engine.setState(true, 0, false, false);
  54035. }
  54036. }
  54037. else {
  54038. // Need to reset refresh rate of the shadowMap
  54039. if (this._shadowMap) {
  54040. this._shadowMap.resetRefreshCounter();
  54041. }
  54042. }
  54043. };
  54044. ShadowGenerator.prototype._applyFilterValues = function () {
  54045. if (!this._shadowMap) {
  54046. return;
  54047. }
  54048. if (this.filter === ShadowGenerator.FILTER_NONE) {
  54049. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  54050. }
  54051. else {
  54052. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54053. }
  54054. };
  54055. /**
  54056. * Force shader compilation including textures ready check
  54057. */
  54058. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  54059. var _this = this;
  54060. var localOptions = __assign({ useInstances: false }, options);
  54061. var shadowMap = this.getShadowMap();
  54062. if (!shadowMap) {
  54063. if (onCompiled) {
  54064. onCompiled(this);
  54065. }
  54066. return;
  54067. }
  54068. var renderList = shadowMap.renderList;
  54069. if (!renderList) {
  54070. if (onCompiled) {
  54071. onCompiled(this);
  54072. }
  54073. return;
  54074. }
  54075. var subMeshes = new Array();
  54076. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  54077. var mesh = renderList_1[_i];
  54078. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  54079. }
  54080. if (subMeshes.length === 0) {
  54081. if (onCompiled) {
  54082. onCompiled(this);
  54083. }
  54084. return;
  54085. }
  54086. var currentIndex = 0;
  54087. var checkReady = function () {
  54088. if (!_this._scene || !_this._scene.getEngine()) {
  54089. return;
  54090. }
  54091. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  54092. currentIndex++;
  54093. if (currentIndex >= subMeshes.length) {
  54094. if (onCompiled) {
  54095. onCompiled(_this);
  54096. }
  54097. return;
  54098. }
  54099. }
  54100. setTimeout(checkReady, 16);
  54101. };
  54102. checkReady();
  54103. };
  54104. /**
  54105. * Boolean : true when the ShadowGenerator is finally computed.
  54106. */
  54107. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  54108. var defines = [];
  54109. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  54110. defines.push("#define FLOAT");
  54111. }
  54112. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  54113. defines.push("#define ESM");
  54114. }
  54115. var attribs = [BABYLON.VertexBuffer.PositionKind];
  54116. var mesh = subMesh.getMesh();
  54117. var material = subMesh.getMaterial();
  54118. // Alpha test
  54119. if (material && material.needAlphaTesting()) {
  54120. var alphaTexture = material.getAlphaTestTexture();
  54121. if (alphaTexture) {
  54122. defines.push("#define ALPHATEST");
  54123. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54124. attribs.push(BABYLON.VertexBuffer.UVKind);
  54125. defines.push("#define UV1");
  54126. }
  54127. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54128. if (alphaTexture.coordinatesIndex === 1) {
  54129. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54130. defines.push("#define UV2");
  54131. }
  54132. }
  54133. }
  54134. }
  54135. // Bones
  54136. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54137. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54138. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54139. if (mesh.numBoneInfluencers > 4) {
  54140. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54141. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54142. }
  54143. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54144. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54145. }
  54146. else {
  54147. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54148. }
  54149. // Instances
  54150. if (useInstances) {
  54151. defines.push("#define INSTANCES");
  54152. attribs.push("world0");
  54153. attribs.push("world1");
  54154. attribs.push("world2");
  54155. attribs.push("world3");
  54156. }
  54157. // Get correct effect
  54158. var join = defines.join("\n");
  54159. if (this._cachedDefines !== join) {
  54160. this._cachedDefines = join;
  54161. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  54162. }
  54163. if (!this._effect.isReady()) {
  54164. return false;
  54165. }
  54166. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  54167. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  54168. this._initializeBlurRTTAndPostProcesses();
  54169. }
  54170. }
  54171. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  54172. return false;
  54173. }
  54174. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  54175. return false;
  54176. }
  54177. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  54178. return false;
  54179. }
  54180. return true;
  54181. };
  54182. /**
  54183. * This creates the defines related to the standard BJS materials.
  54184. */
  54185. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  54186. var scene = this._scene;
  54187. var light = this._light;
  54188. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  54189. return;
  54190. }
  54191. defines["SHADOW" + lightIndex] = true;
  54192. if (this.usePoissonSampling) {
  54193. defines["SHADOWPCF" + lightIndex] = true;
  54194. }
  54195. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  54196. defines["SHADOWESM" + lightIndex] = true;
  54197. }
  54198. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  54199. defines["SHADOWCLOSEESM" + lightIndex] = true;
  54200. }
  54201. if (light.needCube()) {
  54202. defines["SHADOWCUBE" + lightIndex] = true;
  54203. }
  54204. };
  54205. /**
  54206. * This binds shadow lights related to the standard BJS materials.
  54207. * It implies the unifroms available on the materials are the standard BJS ones.
  54208. */
  54209. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  54210. var light = this._light;
  54211. var scene = this._scene;
  54212. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  54213. return;
  54214. }
  54215. var camera = scene.activeCamera;
  54216. if (!camera) {
  54217. return;
  54218. }
  54219. var shadowMap = this.getShadowMap();
  54220. if (!shadowMap) {
  54221. return;
  54222. }
  54223. if (!light.needCube()) {
  54224. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  54225. }
  54226. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  54227. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  54228. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  54229. };
  54230. // Methods
  54231. /**
  54232. * Returns a Matrix object : the updated transformation matrix.
  54233. */
  54234. ShadowGenerator.prototype.getTransformMatrix = function () {
  54235. var scene = this._scene;
  54236. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  54237. return this._transformMatrix;
  54238. }
  54239. this._currentRenderID = scene.getRenderId();
  54240. this._currentFaceIndexCache = this._currentFaceIndex;
  54241. var lightPosition = this._light.position;
  54242. if (this._light.computeTransformedInformation()) {
  54243. lightPosition = this._light.transformedPosition;
  54244. }
  54245. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  54246. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  54247. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  54248. }
  54249. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  54250. this._cachedPosition = lightPosition.clone();
  54251. this._cachedDirection = this._lightDirection.clone();
  54252. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  54253. var shadowMap = this.getShadowMap();
  54254. if (shadowMap) {
  54255. var renderList = shadowMap.renderList;
  54256. if (renderList) {
  54257. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  54258. }
  54259. }
  54260. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  54261. }
  54262. return this._transformMatrix;
  54263. };
  54264. ShadowGenerator.prototype.recreateShadowMap = function () {
  54265. var shadowMap = this._shadowMap;
  54266. if (!shadowMap) {
  54267. return;
  54268. }
  54269. // Track render list.
  54270. var renderList = shadowMap.renderList;
  54271. // Clean up existing data.
  54272. this._disposeRTTandPostProcesses();
  54273. // Reinitializes.
  54274. this._initializeGenerator();
  54275. // Reaffect the filter to ensure a correct fallback if necessary.
  54276. this.filter = this.filter;
  54277. // Reaffect the filter.
  54278. this._applyFilterValues();
  54279. // Reaffect Render List.
  54280. this._shadowMap.renderList = renderList;
  54281. };
  54282. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  54283. if (this._shadowMap2) {
  54284. this._shadowMap2.dispose();
  54285. this._shadowMap2 = null;
  54286. }
  54287. if (this._boxBlurPostprocess) {
  54288. this._boxBlurPostprocess.dispose();
  54289. this._boxBlurPostprocess = null;
  54290. }
  54291. if (this._kernelBlurXPostprocess) {
  54292. this._kernelBlurXPostprocess.dispose();
  54293. this._kernelBlurXPostprocess = null;
  54294. }
  54295. if (this._kernelBlurYPostprocess) {
  54296. this._kernelBlurYPostprocess.dispose();
  54297. this._kernelBlurYPostprocess = null;
  54298. }
  54299. this._blurPostProcesses = [];
  54300. };
  54301. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  54302. if (this._shadowMap) {
  54303. this._shadowMap.dispose();
  54304. this._shadowMap = null;
  54305. }
  54306. this._disposeBlurPostProcesses();
  54307. };
  54308. /**
  54309. * Disposes the ShadowGenerator.
  54310. * Returns nothing.
  54311. */
  54312. ShadowGenerator.prototype.dispose = function () {
  54313. this._disposeRTTandPostProcesses();
  54314. if (this._light) {
  54315. this._light._shadowGenerator = null;
  54316. this._light._markMeshesAsLightDirty();
  54317. }
  54318. };
  54319. /**
  54320. * Serializes the ShadowGenerator and returns a serializationObject.
  54321. */
  54322. ShadowGenerator.prototype.serialize = function () {
  54323. var serializationObject = {};
  54324. var shadowMap = this.getShadowMap();
  54325. if (!shadowMap) {
  54326. return serializationObject;
  54327. }
  54328. serializationObject.lightId = this._light.id;
  54329. serializationObject.mapSize = shadowMap.getRenderSize();
  54330. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  54331. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  54332. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  54333. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  54334. serializationObject.usePoissonSampling = this.usePoissonSampling;
  54335. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  54336. serializationObject.depthScale = this.depthScale;
  54337. serializationObject.darkness = this.getDarkness();
  54338. serializationObject.blurBoxOffset = this.blurBoxOffset;
  54339. serializationObject.blurKernel = this.blurKernel;
  54340. serializationObject.blurScale = this.blurScale;
  54341. serializationObject.useKernelBlur = this.useKernelBlur;
  54342. serializationObject.transparencyShadow = this._transparencyShadow;
  54343. serializationObject.renderList = [];
  54344. if (shadowMap.renderList) {
  54345. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  54346. var mesh = shadowMap.renderList[meshIndex];
  54347. serializationObject.renderList.push(mesh.id);
  54348. }
  54349. }
  54350. return serializationObject;
  54351. };
  54352. /**
  54353. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  54354. */
  54355. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  54356. //casting to point light, as light is missing the position attr and typescript complains.
  54357. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  54358. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  54359. var shadowMap = shadowGenerator.getShadowMap();
  54360. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  54361. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  54362. meshes.forEach(function (mesh) {
  54363. if (!shadowMap) {
  54364. return;
  54365. }
  54366. if (!shadowMap.renderList) {
  54367. shadowMap.renderList = [];
  54368. }
  54369. shadowMap.renderList.push(mesh);
  54370. });
  54371. }
  54372. if (parsedShadowGenerator.usePoissonSampling) {
  54373. shadowGenerator.usePoissonSampling = true;
  54374. }
  54375. else if (parsedShadowGenerator.useExponentialShadowMap) {
  54376. shadowGenerator.useExponentialShadowMap = true;
  54377. }
  54378. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  54379. shadowGenerator.useBlurExponentialShadowMap = true;
  54380. }
  54381. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  54382. shadowGenerator.useCloseExponentialShadowMap = true;
  54383. }
  54384. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  54385. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  54386. }
  54387. else if (parsedShadowGenerator.useVarianceShadowMap) {
  54388. shadowGenerator.useExponentialShadowMap = true;
  54389. }
  54390. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  54391. shadowGenerator.useBlurExponentialShadowMap = true;
  54392. }
  54393. if (parsedShadowGenerator.depthScale) {
  54394. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  54395. }
  54396. if (parsedShadowGenerator.blurScale) {
  54397. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  54398. }
  54399. if (parsedShadowGenerator.blurBoxOffset) {
  54400. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  54401. }
  54402. if (parsedShadowGenerator.useKernelBlur) {
  54403. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  54404. }
  54405. if (parsedShadowGenerator.blurKernel) {
  54406. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  54407. }
  54408. if (parsedShadowGenerator.bias !== undefined) {
  54409. shadowGenerator.bias = parsedShadowGenerator.bias;
  54410. }
  54411. if (parsedShadowGenerator.darkness) {
  54412. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  54413. }
  54414. if (parsedShadowGenerator.transparencyShadow) {
  54415. shadowGenerator.setTransparencyShadow(true);
  54416. }
  54417. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  54418. return shadowGenerator;
  54419. };
  54420. ShadowGenerator._FILTER_NONE = 0;
  54421. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  54422. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  54423. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  54424. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  54425. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  54426. return ShadowGenerator;
  54427. }());
  54428. BABYLON.ShadowGenerator = ShadowGenerator;
  54429. })(BABYLON || (BABYLON = {}));
  54430. //# sourceMappingURL=babylon.shadowGenerator.js.map
  54431. var BABYLON;
  54432. (function (BABYLON) {
  54433. var DefaultLoadingScreen = /** @class */ (function () {
  54434. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  54435. if (_loadingText === void 0) { _loadingText = ""; }
  54436. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  54437. var _this = this;
  54438. this._renderingCanvas = _renderingCanvas;
  54439. this._loadingText = _loadingText;
  54440. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  54441. // Resize
  54442. this._resizeLoadingUI = function () {
  54443. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  54444. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  54445. if (!_this._loadingDiv) {
  54446. return;
  54447. }
  54448. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  54449. _this._loadingDiv.style.left = canvasRect.left + "px";
  54450. _this._loadingDiv.style.top = canvasRect.top + "px";
  54451. _this._loadingDiv.style.width = canvasRect.width + "px";
  54452. _this._loadingDiv.style.height = canvasRect.height + "px";
  54453. };
  54454. }
  54455. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  54456. if (this._loadingDiv) {
  54457. // Do not add a loading screen if there is already one
  54458. return;
  54459. }
  54460. this._loadingDiv = document.createElement("div");
  54461. this._loadingDiv.id = "babylonjsLoadingDiv";
  54462. this._loadingDiv.style.opacity = "0";
  54463. this._loadingDiv.style.transition = "opacity 1.5s ease";
  54464. this._loadingDiv.style.pointerEvents = "none";
  54465. // Loading text
  54466. this._loadingTextDiv = document.createElement("div");
  54467. this._loadingTextDiv.style.position = "absolute";
  54468. this._loadingTextDiv.style.left = "0";
  54469. this._loadingTextDiv.style.top = "50%";
  54470. this._loadingTextDiv.style.marginTop = "80px";
  54471. this._loadingTextDiv.style.width = "100%";
  54472. this._loadingTextDiv.style.height = "20px";
  54473. this._loadingTextDiv.style.fontFamily = "Arial";
  54474. this._loadingTextDiv.style.fontSize = "14px";
  54475. this._loadingTextDiv.style.color = "white";
  54476. this._loadingTextDiv.style.textAlign = "center";
  54477. this._loadingTextDiv.innerHTML = "Loading";
  54478. this._loadingDiv.appendChild(this._loadingTextDiv);
  54479. //set the predefined text
  54480. this._loadingTextDiv.innerHTML = this._loadingText;
  54481. // Generating keyframes
  54482. var style = document.createElement('style');
  54483. style.type = 'text/css';
  54484. 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 }";
  54485. style.innerHTML = keyFrames;
  54486. document.getElementsByTagName('head')[0].appendChild(style);
  54487. // Loading img
  54488. var imgBack = new Image();
  54489. 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";
  54490. imgBack.style.position = "absolute";
  54491. imgBack.style.left = "50%";
  54492. imgBack.style.top = "50%";
  54493. imgBack.style.marginLeft = "-60px";
  54494. imgBack.style.marginTop = "-60px";
  54495. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  54496. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  54497. imgBack.style.transformOrigin = "50% 50%";
  54498. imgBack.style.webkitTransformOrigin = "50% 50%";
  54499. this._loadingDiv.appendChild(imgBack);
  54500. this._resizeLoadingUI();
  54501. window.addEventListener("resize", this._resizeLoadingUI);
  54502. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  54503. document.body.appendChild(this._loadingDiv);
  54504. this._loadingDiv.style.opacity = "1";
  54505. };
  54506. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  54507. var _this = this;
  54508. if (!this._loadingDiv) {
  54509. return;
  54510. }
  54511. var onTransitionEnd = function () {
  54512. if (!_this._loadingDiv) {
  54513. return;
  54514. }
  54515. document.body.removeChild(_this._loadingDiv);
  54516. window.removeEventListener("resize", _this._resizeLoadingUI);
  54517. _this._loadingDiv = null;
  54518. };
  54519. this._loadingDiv.style.opacity = "0";
  54520. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  54521. };
  54522. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  54523. set: function (text) {
  54524. this._loadingText = text;
  54525. if (this._loadingTextDiv) {
  54526. this._loadingTextDiv.innerHTML = this._loadingText;
  54527. }
  54528. },
  54529. enumerable: true,
  54530. configurable: true
  54531. });
  54532. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  54533. get: function () {
  54534. return this._loadingDivBackgroundColor;
  54535. },
  54536. set: function (color) {
  54537. this._loadingDivBackgroundColor = color;
  54538. if (!this._loadingDiv) {
  54539. return;
  54540. }
  54541. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  54542. },
  54543. enumerable: true,
  54544. configurable: true
  54545. });
  54546. return DefaultLoadingScreen;
  54547. }());
  54548. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  54549. })(BABYLON || (BABYLON = {}));
  54550. //# sourceMappingURL=babylon.loadingScreen.js.map
  54551. var BABYLON;
  54552. (function (BABYLON) {
  54553. var SceneLoaderProgressEvent = /** @class */ (function () {
  54554. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  54555. this.lengthComputable = lengthComputable;
  54556. this.loaded = loaded;
  54557. this.total = total;
  54558. }
  54559. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  54560. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  54561. };
  54562. return SceneLoaderProgressEvent;
  54563. }());
  54564. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  54565. var SceneLoader = /** @class */ (function () {
  54566. function SceneLoader() {
  54567. }
  54568. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  54569. get: function () {
  54570. return 0;
  54571. },
  54572. enumerable: true,
  54573. configurable: true
  54574. });
  54575. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  54576. get: function () {
  54577. return 1;
  54578. },
  54579. enumerable: true,
  54580. configurable: true
  54581. });
  54582. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  54583. get: function () {
  54584. return 2;
  54585. },
  54586. enumerable: true,
  54587. configurable: true
  54588. });
  54589. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  54590. get: function () {
  54591. return 3;
  54592. },
  54593. enumerable: true,
  54594. configurable: true
  54595. });
  54596. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  54597. get: function () {
  54598. return SceneLoader._ForceFullSceneLoadingForIncremental;
  54599. },
  54600. set: function (value) {
  54601. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  54602. },
  54603. enumerable: true,
  54604. configurable: true
  54605. });
  54606. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  54607. get: function () {
  54608. return SceneLoader._ShowLoadingScreen;
  54609. },
  54610. set: function (value) {
  54611. SceneLoader._ShowLoadingScreen = value;
  54612. },
  54613. enumerable: true,
  54614. configurable: true
  54615. });
  54616. Object.defineProperty(SceneLoader, "loggingLevel", {
  54617. get: function () {
  54618. return SceneLoader._loggingLevel;
  54619. },
  54620. set: function (value) {
  54621. SceneLoader._loggingLevel = value;
  54622. },
  54623. enumerable: true,
  54624. configurable: true
  54625. });
  54626. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  54627. get: function () {
  54628. return SceneLoader._CleanBoneMatrixWeights;
  54629. },
  54630. set: function (value) {
  54631. SceneLoader._CleanBoneMatrixWeights = value;
  54632. },
  54633. enumerable: true,
  54634. configurable: true
  54635. });
  54636. SceneLoader._getDefaultPlugin = function () {
  54637. return SceneLoader._registeredPlugins[".babylon"];
  54638. };
  54639. SceneLoader._getPluginForExtension = function (extension) {
  54640. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  54641. if (registeredPlugin) {
  54642. return registeredPlugin;
  54643. }
  54644. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  54645. return SceneLoader._getDefaultPlugin();
  54646. };
  54647. SceneLoader._getPluginForDirectLoad = function (data) {
  54648. for (var extension in SceneLoader._registeredPlugins) {
  54649. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  54650. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  54651. return SceneLoader._registeredPlugins[extension];
  54652. }
  54653. }
  54654. return SceneLoader._getDefaultPlugin();
  54655. };
  54656. SceneLoader._getPluginForFilename = function (sceneFilename) {
  54657. if (sceneFilename.name) {
  54658. sceneFilename = sceneFilename.name;
  54659. }
  54660. var queryStringPosition = sceneFilename.indexOf("?");
  54661. if (queryStringPosition !== -1) {
  54662. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  54663. }
  54664. var dotPosition = sceneFilename.lastIndexOf(".");
  54665. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  54666. return SceneLoader._getPluginForExtension(extension);
  54667. };
  54668. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  54669. SceneLoader._getDirectLoad = function (sceneFilename) {
  54670. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  54671. return sceneFilename.substr(5);
  54672. }
  54673. return null;
  54674. };
  54675. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  54676. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  54677. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  54678. var plugin;
  54679. if (registeredPlugin.plugin.createPlugin) {
  54680. plugin = registeredPlugin.plugin.createPlugin();
  54681. }
  54682. else {
  54683. plugin = registeredPlugin.plugin;
  54684. }
  54685. var useArrayBuffer = registeredPlugin.isBinary;
  54686. var database;
  54687. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  54688. var dataCallback = function (data, responseURL) {
  54689. if (scene.isDisposed) {
  54690. onError("Scene has been disposed");
  54691. return;
  54692. }
  54693. scene.database = database;
  54694. onSuccess(plugin, data, responseURL);
  54695. };
  54696. var request = null;
  54697. var pluginDisposed = false;
  54698. var onDisposeObservable = plugin.onDisposeObservable;
  54699. if (onDisposeObservable) {
  54700. onDisposeObservable.add(function () {
  54701. pluginDisposed = true;
  54702. if (request) {
  54703. request.abort();
  54704. request = null;
  54705. }
  54706. onDispose();
  54707. });
  54708. }
  54709. var manifestChecked = function () {
  54710. if (pluginDisposed) {
  54711. return;
  54712. }
  54713. var url = rootUrl + sceneFilename;
  54714. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  54715. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  54716. } : undefined, database, useArrayBuffer, function (request, exception) {
  54717. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  54718. });
  54719. };
  54720. if (directLoad) {
  54721. dataCallback(directLoad);
  54722. return plugin;
  54723. }
  54724. if (rootUrl.indexOf("file:") === -1) {
  54725. if (scene.getEngine().enableOfflineSupport) {
  54726. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  54727. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  54728. }
  54729. else {
  54730. manifestChecked();
  54731. }
  54732. }
  54733. else {
  54734. var fileOrString = sceneFilename;
  54735. if (fileOrString.name) {
  54736. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  54737. }
  54738. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  54739. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  54740. }
  54741. else {
  54742. onError("Unable to find file named " + sceneFilename);
  54743. }
  54744. }
  54745. return plugin;
  54746. };
  54747. // Public functions
  54748. SceneLoader.GetPluginForExtension = function (extension) {
  54749. return SceneLoader._getPluginForExtension(extension).plugin;
  54750. };
  54751. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  54752. return !!SceneLoader._registeredPlugins[extension];
  54753. };
  54754. SceneLoader.RegisterPlugin = function (plugin) {
  54755. if (typeof plugin.extensions === "string") {
  54756. var extension = plugin.extensions;
  54757. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54758. plugin: plugin,
  54759. isBinary: false
  54760. };
  54761. }
  54762. else {
  54763. var extensions = plugin.extensions;
  54764. Object.keys(extensions).forEach(function (extension) {
  54765. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54766. plugin: plugin,
  54767. isBinary: extensions[extension].isBinary
  54768. };
  54769. });
  54770. }
  54771. };
  54772. /**
  54773. * Import meshes into a scene
  54774. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  54775. * @param rootUrl a string that defines the root url for scene and resources
  54776. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54777. * @param scene the instance of BABYLON.Scene to append to
  54778. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  54779. * @param onProgress a callback with a progress event for each file being loaded
  54780. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54781. */
  54782. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54783. if (onSuccess === void 0) { onSuccess = null; }
  54784. if (onProgress === void 0) { onProgress = null; }
  54785. if (onError === void 0) { onError = null; }
  54786. if (pluginExtension === void 0) { pluginExtension = null; }
  54787. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54788. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54789. return null;
  54790. }
  54791. var loadingToken = {};
  54792. scene._addPendingData(loadingToken);
  54793. var disposeHandler = function () {
  54794. scene._removePendingData(loadingToken);
  54795. };
  54796. var errorHandler = function (message, exception) {
  54797. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  54798. if (onError) {
  54799. onError(scene, errorMessage, exception);
  54800. }
  54801. else {
  54802. BABYLON.Tools.Error(errorMessage);
  54803. // should the exception be thrown?
  54804. }
  54805. disposeHandler();
  54806. };
  54807. var progressHandler = onProgress ? function (event) {
  54808. try {
  54809. onProgress(event);
  54810. }
  54811. catch (e) {
  54812. errorHandler("Error in onProgress callback", e);
  54813. }
  54814. } : undefined;
  54815. var successHandler = function (meshes, particleSystems, skeletons) {
  54816. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  54817. if (onSuccess) {
  54818. try {
  54819. onSuccess(meshes, particleSystems, skeletons);
  54820. }
  54821. catch (e) {
  54822. errorHandler("Error in onSuccess callback", e);
  54823. }
  54824. }
  54825. scene._removePendingData(loadingToken);
  54826. };
  54827. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54828. if (plugin.rewriteRootURL) {
  54829. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  54830. }
  54831. if (plugin.importMesh) {
  54832. var syncedPlugin = plugin;
  54833. var meshes = new Array();
  54834. var particleSystems = new Array();
  54835. var skeletons = new Array();
  54836. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  54837. return;
  54838. }
  54839. scene.loadingPluginName = plugin.name;
  54840. successHandler(meshes, particleSystems, skeletons);
  54841. }
  54842. else {
  54843. var asyncedPlugin = plugin;
  54844. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  54845. scene.loadingPluginName = plugin.name;
  54846. successHandler(meshes, particleSystems, skeletons);
  54847. }, progressHandler, errorHandler);
  54848. }
  54849. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54850. };
  54851. /**
  54852. * Load a scene
  54853. * @param rootUrl a string that defines the root url for scene and resources
  54854. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54855. * @param engine is the instance of BABYLON.Engine to use to create the scene
  54856. * @param onSuccess a callback with the scene when import succeeds
  54857. * @param onProgress a callback with a progress event for each file being loaded
  54858. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54859. */
  54860. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  54861. if (onSuccess === void 0) { onSuccess = null; }
  54862. if (onProgress === void 0) { onProgress = null; }
  54863. if (onError === void 0) { onError = null; }
  54864. if (pluginExtension === void 0) { pluginExtension = null; }
  54865. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  54866. };
  54867. /**
  54868. * Append a scene
  54869. * @param rootUrl a string that defines the root url for scene and resources
  54870. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54871. * @param scene is the instance of BABYLON.Scene to append to
  54872. * @param onSuccess a callback with the scene when import succeeds
  54873. * @param onProgress a callback with a progress event for each file being loaded
  54874. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54875. */
  54876. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54877. if (onSuccess === void 0) { onSuccess = null; }
  54878. if (onProgress === void 0) { onProgress = null; }
  54879. if (onError === void 0) { onError = null; }
  54880. if (pluginExtension === void 0) { pluginExtension = null; }
  54881. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54882. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54883. return null;
  54884. }
  54885. if (SceneLoader.ShowLoadingScreen) {
  54886. scene.getEngine().displayLoadingUI();
  54887. }
  54888. var loadingToken = {};
  54889. scene._addPendingData(loadingToken);
  54890. var disposeHandler = function () {
  54891. scene._removePendingData(loadingToken);
  54892. scene.getEngine().hideLoadingUI();
  54893. };
  54894. var errorHandler = function (message, exception) {
  54895. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  54896. if (onError) {
  54897. onError(scene, errorMessage, exception);
  54898. }
  54899. else {
  54900. BABYLON.Tools.Error(errorMessage);
  54901. // should the exception be thrown?
  54902. }
  54903. disposeHandler();
  54904. };
  54905. var progressHandler = onProgress ? function (event) {
  54906. try {
  54907. onProgress(event);
  54908. }
  54909. catch (e) {
  54910. errorHandler("Error in onProgress callback", e);
  54911. }
  54912. } : undefined;
  54913. var successHandler = function () {
  54914. if (onSuccess) {
  54915. try {
  54916. onSuccess(scene);
  54917. }
  54918. catch (e) {
  54919. errorHandler("Error in onSuccess callback", e);
  54920. }
  54921. }
  54922. scene._removePendingData(loadingToken);
  54923. };
  54924. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54925. if (plugin.load) {
  54926. var syncedPlugin = plugin;
  54927. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  54928. return;
  54929. }
  54930. scene.loadingPluginName = plugin.name;
  54931. successHandler();
  54932. }
  54933. else {
  54934. var asyncedPlugin = plugin;
  54935. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  54936. scene.loadingPluginName = plugin.name;
  54937. successHandler();
  54938. }, progressHandler, errorHandler);
  54939. }
  54940. if (SceneLoader.ShowLoadingScreen) {
  54941. scene.executeWhenReady(function () {
  54942. scene.getEngine().hideLoadingUI();
  54943. });
  54944. }
  54945. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54946. };
  54947. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54948. if (onSuccess === void 0) { onSuccess = null; }
  54949. if (onProgress === void 0) { onProgress = null; }
  54950. if (onError === void 0) { onError = null; }
  54951. if (pluginExtension === void 0) { pluginExtension = null; }
  54952. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54953. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54954. return null;
  54955. }
  54956. var loadingToken = {};
  54957. scene._addPendingData(loadingToken);
  54958. var disposeHandler = function () {
  54959. scene._removePendingData(loadingToken);
  54960. };
  54961. var errorHandler = function (message, exception) {
  54962. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  54963. if (onError) {
  54964. onError(scene, errorMessage, exception);
  54965. }
  54966. else {
  54967. BABYLON.Tools.Error(errorMessage);
  54968. // should the exception be thrown?
  54969. }
  54970. disposeHandler();
  54971. };
  54972. var progressHandler = onProgress ? function (event) {
  54973. try {
  54974. onProgress(event);
  54975. }
  54976. catch (e) {
  54977. errorHandler("Error in onProgress callback", e);
  54978. }
  54979. } : undefined;
  54980. var successHandler = function (assets) {
  54981. if (onSuccess) {
  54982. try {
  54983. onSuccess(assets);
  54984. }
  54985. catch (e) {
  54986. errorHandler("Error in onSuccess callback", e);
  54987. }
  54988. }
  54989. scene._removePendingData(loadingToken);
  54990. };
  54991. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54992. if (plugin.loadAssets) {
  54993. var syncedPlugin = plugin;
  54994. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  54995. if (!assetContainer) {
  54996. return;
  54997. }
  54998. scene.loadingPluginName = plugin.name;
  54999. successHandler(assetContainer);
  55000. }
  55001. else if (plugin.loadAssetsAsync) {
  55002. var asyncedPlugin = plugin;
  55003. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  55004. if (assetContainer) {
  55005. scene.loadingPluginName = plugin.name;
  55006. successHandler(assetContainer);
  55007. }
  55008. }, progressHandler, errorHandler);
  55009. }
  55010. else {
  55011. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  55012. }
  55013. if (SceneLoader.ShowLoadingScreen) {
  55014. scene.executeWhenReady(function () {
  55015. scene.getEngine().hideLoadingUI();
  55016. });
  55017. }
  55018. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  55019. };
  55020. // Flags
  55021. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  55022. SceneLoader._ShowLoadingScreen = true;
  55023. SceneLoader._CleanBoneMatrixWeights = false;
  55024. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  55025. // Members
  55026. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  55027. SceneLoader._registeredPlugins = {};
  55028. return SceneLoader;
  55029. }());
  55030. BABYLON.SceneLoader = SceneLoader;
  55031. ;
  55032. })(BABYLON || (BABYLON = {}));
  55033. //# sourceMappingURL=babylon.sceneLoader.js.map
  55034. var BABYLON;
  55035. (function (BABYLON) {
  55036. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  55037. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  55038. var parsedMaterial = parsedData.materials[index];
  55039. if (parsedMaterial.id === id) {
  55040. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  55041. }
  55042. }
  55043. return null;
  55044. };
  55045. var isDescendantOf = function (mesh, names, hierarchyIds) {
  55046. for (var i in names) {
  55047. if (mesh.name === names[i]) {
  55048. hierarchyIds.push(mesh.id);
  55049. return true;
  55050. }
  55051. }
  55052. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  55053. hierarchyIds.push(mesh.id);
  55054. return true;
  55055. }
  55056. return false;
  55057. };
  55058. var logOperation = function (operation, producer) {
  55059. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  55060. };
  55061. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  55062. if (addToScene === void 0) { addToScene = false; }
  55063. var container = new BABYLON.AssetContainer(scene);
  55064. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  55065. // when SceneLoader.debugLogging = true (default), or exception encountered.
  55066. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  55067. // and avoid problems with multiple concurrent .babylon loads.
  55068. var log = "importScene has failed JSON parse";
  55069. try {
  55070. var parsedData = JSON.parse(data);
  55071. log = "";
  55072. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  55073. var index;
  55074. var cache;
  55075. // Lights
  55076. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  55077. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  55078. var parsedLight = parsedData.lights[index];
  55079. var light = BABYLON.Light.Parse(parsedLight, scene);
  55080. if (light) {
  55081. container.lights.push(light);
  55082. log += (index === 0 ? "\n\tLights:" : "");
  55083. log += "\n\t\t" + light.toString(fullDetails);
  55084. }
  55085. }
  55086. }
  55087. // Animations
  55088. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  55089. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  55090. var parsedAnimation = parsedData.animations[index];
  55091. var animation = BABYLON.Animation.Parse(parsedAnimation);
  55092. scene.animations.push(animation);
  55093. container.animations.push(animation);
  55094. log += (index === 0 ? "\n\tAnimations:" : "");
  55095. log += "\n\t\t" + animation.toString(fullDetails);
  55096. }
  55097. }
  55098. // Materials
  55099. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  55100. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  55101. var parsedMaterial = parsedData.materials[index];
  55102. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  55103. container.materials.push(mat);
  55104. log += (index === 0 ? "\n\tMaterials:" : "");
  55105. log += "\n\t\t" + mat.toString(fullDetails);
  55106. }
  55107. }
  55108. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  55109. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  55110. var parsedMultiMaterial = parsedData.multiMaterials[index];
  55111. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  55112. container.multiMaterials.push(mmat);
  55113. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  55114. log += "\n\t\t" + mmat.toString(fullDetails);
  55115. }
  55116. }
  55117. // Morph targets
  55118. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  55119. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  55120. var managerData = _a[_i];
  55121. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  55122. }
  55123. }
  55124. // Skeletons
  55125. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  55126. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  55127. var parsedSkeleton = parsedData.skeletons[index];
  55128. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  55129. container.skeletons.push(skeleton);
  55130. log += (index === 0 ? "\n\tSkeletons:" : "");
  55131. log += "\n\t\t" + skeleton.toString(fullDetails);
  55132. }
  55133. }
  55134. // Geometries
  55135. var geometries = parsedData.geometries;
  55136. if (geometries !== undefined && geometries !== null) {
  55137. var addedGeometry = new Array();
  55138. // Boxes
  55139. var boxes = geometries.boxes;
  55140. if (boxes !== undefined && boxes !== null) {
  55141. for (index = 0, cache = boxes.length; index < cache; index++) {
  55142. var parsedBox = boxes[index];
  55143. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  55144. }
  55145. }
  55146. // Spheres
  55147. var spheres = geometries.spheres;
  55148. if (spheres !== undefined && spheres !== null) {
  55149. for (index = 0, cache = spheres.length; index < cache; index++) {
  55150. var parsedSphere = spheres[index];
  55151. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  55152. }
  55153. }
  55154. // Cylinders
  55155. var cylinders = geometries.cylinders;
  55156. if (cylinders !== undefined && cylinders !== null) {
  55157. for (index = 0, cache = cylinders.length; index < cache; index++) {
  55158. var parsedCylinder = cylinders[index];
  55159. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  55160. }
  55161. }
  55162. // Toruses
  55163. var toruses = geometries.toruses;
  55164. if (toruses !== undefined && toruses !== null) {
  55165. for (index = 0, cache = toruses.length; index < cache; index++) {
  55166. var parsedTorus = toruses[index];
  55167. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  55168. }
  55169. }
  55170. // Grounds
  55171. var grounds = geometries.grounds;
  55172. if (grounds !== undefined && grounds !== null) {
  55173. for (index = 0, cache = grounds.length; index < cache; index++) {
  55174. var parsedGround = grounds[index];
  55175. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  55176. }
  55177. }
  55178. // Planes
  55179. var planes = geometries.planes;
  55180. if (planes !== undefined && planes !== null) {
  55181. for (index = 0, cache = planes.length; index < cache; index++) {
  55182. var parsedPlane = planes[index];
  55183. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  55184. }
  55185. }
  55186. // TorusKnots
  55187. var torusKnots = geometries.torusKnots;
  55188. if (torusKnots !== undefined && torusKnots !== null) {
  55189. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  55190. var parsedTorusKnot = torusKnots[index];
  55191. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  55192. }
  55193. }
  55194. // VertexData
  55195. var vertexData = geometries.vertexData;
  55196. if (vertexData !== undefined && vertexData !== null) {
  55197. for (index = 0, cache = vertexData.length; index < cache; index++) {
  55198. var parsedVertexData = vertexData[index];
  55199. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  55200. }
  55201. }
  55202. addedGeometry.forEach(function (g) {
  55203. if (g) {
  55204. container.geometries.push(g);
  55205. }
  55206. });
  55207. }
  55208. // Transform nodes
  55209. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  55210. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  55211. var parsedTransformNode = parsedData.transformNodes[index];
  55212. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  55213. container.transformNodes.push(node);
  55214. }
  55215. }
  55216. // Meshes
  55217. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  55218. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  55219. var parsedMesh = parsedData.meshes[index];
  55220. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  55221. container.meshes.push(mesh);
  55222. log += (index === 0 ? "\n\tMeshes:" : "");
  55223. log += "\n\t\t" + mesh.toString(fullDetails);
  55224. }
  55225. }
  55226. // Cameras
  55227. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  55228. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  55229. var parsedCamera = parsedData.cameras[index];
  55230. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  55231. container.cameras.push(camera);
  55232. log += (index === 0 ? "\n\tCameras:" : "");
  55233. log += "\n\t\t" + camera.toString(fullDetails);
  55234. }
  55235. }
  55236. // Browsing all the graph to connect the dots
  55237. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  55238. var camera = scene.cameras[index];
  55239. if (camera._waitingParentId) {
  55240. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  55241. camera._waitingParentId = null;
  55242. }
  55243. }
  55244. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  55245. var light_1 = scene.lights[index];
  55246. if (light_1 && light_1._waitingParentId) {
  55247. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  55248. light_1._waitingParentId = null;
  55249. }
  55250. }
  55251. // Sounds
  55252. // TODO: add sound
  55253. var loadedSounds = [];
  55254. var loadedSound;
  55255. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  55256. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  55257. var parsedSound = parsedData.sounds[index];
  55258. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55259. if (!parsedSound.url)
  55260. parsedSound.url = parsedSound.name;
  55261. if (!loadedSounds[parsedSound.url]) {
  55262. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  55263. loadedSounds[parsedSound.url] = loadedSound;
  55264. container.sounds.push(loadedSound);
  55265. }
  55266. else {
  55267. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  55268. }
  55269. }
  55270. else {
  55271. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  55272. }
  55273. }
  55274. }
  55275. loadedSounds = [];
  55276. // Connect parents & children and parse actions
  55277. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  55278. var transformNode = scene.transformNodes[index];
  55279. if (transformNode._waitingParentId) {
  55280. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  55281. transformNode._waitingParentId = null;
  55282. }
  55283. }
  55284. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55285. var mesh = scene.meshes[index];
  55286. if (mesh._waitingParentId) {
  55287. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  55288. mesh._waitingParentId = null;
  55289. }
  55290. if (mesh._waitingActions) {
  55291. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  55292. mesh._waitingActions = null;
  55293. }
  55294. }
  55295. // freeze world matrix application
  55296. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55297. var currentMesh = scene.meshes[index];
  55298. if (currentMesh._waitingFreezeWorldMatrix) {
  55299. currentMesh.freezeWorldMatrix();
  55300. currentMesh._waitingFreezeWorldMatrix = null;
  55301. }
  55302. else {
  55303. currentMesh.computeWorldMatrix(true);
  55304. }
  55305. }
  55306. // Particles Systems
  55307. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  55308. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  55309. var parsedParticleSystem = parsedData.particleSystems[index];
  55310. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  55311. container.particleSystems.push(ps);
  55312. }
  55313. }
  55314. // Lens flares
  55315. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  55316. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  55317. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  55318. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  55319. container.lensFlareSystems.push(lf);
  55320. }
  55321. }
  55322. // Shadows
  55323. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  55324. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  55325. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  55326. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  55327. container.shadowGenerators.push(sg);
  55328. }
  55329. }
  55330. // Lights exclusions / inclusions
  55331. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  55332. var light_2 = scene.lights[index];
  55333. // Excluded check
  55334. if (light_2._excludedMeshesIds.length > 0) {
  55335. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  55336. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  55337. if (excludedMesh) {
  55338. light_2.excludedMeshes.push(excludedMesh);
  55339. }
  55340. }
  55341. light_2._excludedMeshesIds = [];
  55342. }
  55343. // Included check
  55344. if (light_2._includedOnlyMeshesIds.length > 0) {
  55345. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  55346. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  55347. if (includedOnlyMesh) {
  55348. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  55349. }
  55350. }
  55351. light_2._includedOnlyMeshesIds = [];
  55352. }
  55353. }
  55354. // Actions (scene)
  55355. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  55356. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  55357. }
  55358. if (!addToScene) {
  55359. container.removeAllFromScene();
  55360. }
  55361. return container;
  55362. }
  55363. catch (err) {
  55364. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  55365. if (onError) {
  55366. onError(msg, err);
  55367. }
  55368. else {
  55369. BABYLON.Tools.Log(msg);
  55370. throw err;
  55371. }
  55372. }
  55373. finally {
  55374. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55375. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55376. }
  55377. }
  55378. return null;
  55379. };
  55380. BABYLON.SceneLoader.RegisterPlugin({
  55381. name: "babylon.js",
  55382. extensions: ".babylon",
  55383. canDirectLoad: function (data) {
  55384. if (data.indexOf("babylon") !== -1) {
  55385. return true;
  55386. }
  55387. return false;
  55388. },
  55389. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  55390. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  55391. // when SceneLoader.debugLogging = true (default), or exception encountered.
  55392. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  55393. // and avoid problems with multiple concurrent .babylon loads.
  55394. var log = "importMesh has failed JSON parse";
  55395. try {
  55396. var parsedData = JSON.parse(data);
  55397. log = "";
  55398. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  55399. if (!meshesNames) {
  55400. meshesNames = null;
  55401. }
  55402. else if (!Array.isArray(meshesNames)) {
  55403. meshesNames = [meshesNames];
  55404. }
  55405. var hierarchyIds = new Array();
  55406. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  55407. var loadedSkeletonsIds = [];
  55408. var loadedMaterialsIds = [];
  55409. var index;
  55410. var cache;
  55411. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  55412. var parsedMesh = parsedData.meshes[index];
  55413. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  55414. if (meshesNames !== null) {
  55415. // Remove found mesh name from list.
  55416. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  55417. }
  55418. //Geometry?
  55419. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  55420. //does the file contain geometries?
  55421. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  55422. //find the correct geometry and add it to the scene
  55423. var found = false;
  55424. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  55425. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  55426. return;
  55427. }
  55428. else {
  55429. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  55430. if (parsedGeometryData.id === parsedMesh.geometryId) {
  55431. switch (geometryType) {
  55432. case "boxes":
  55433. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  55434. break;
  55435. case "spheres":
  55436. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  55437. break;
  55438. case "cylinders":
  55439. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  55440. break;
  55441. case "toruses":
  55442. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  55443. break;
  55444. case "grounds":
  55445. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  55446. break;
  55447. case "planes":
  55448. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  55449. break;
  55450. case "torusKnots":
  55451. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  55452. break;
  55453. case "vertexData":
  55454. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  55455. break;
  55456. }
  55457. found = true;
  55458. }
  55459. });
  55460. }
  55461. });
  55462. if (found === false) {
  55463. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  55464. }
  55465. }
  55466. }
  55467. // Material ?
  55468. if (parsedMesh.materialId) {
  55469. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  55470. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  55471. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  55472. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  55473. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  55474. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  55475. var subMatId = parsedMultiMaterial.materials[matIndex];
  55476. loadedMaterialsIds.push(subMatId);
  55477. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  55478. log += "\n\tMaterial " + mat.toString(fullDetails);
  55479. }
  55480. loadedMaterialsIds.push(parsedMultiMaterial.id);
  55481. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  55482. materialFound = true;
  55483. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  55484. break;
  55485. }
  55486. }
  55487. }
  55488. if (materialFound === false) {
  55489. loadedMaterialsIds.push(parsedMesh.materialId);
  55490. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  55491. if (!mat) {
  55492. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  55493. }
  55494. else {
  55495. log += "\n\tMaterial " + mat.toString(fullDetails);
  55496. }
  55497. }
  55498. }
  55499. // Skeleton ?
  55500. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  55501. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  55502. if (skeletonAlreadyLoaded === false) {
  55503. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  55504. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  55505. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  55506. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  55507. skeletons.push(skeleton);
  55508. loadedSkeletonsIds.push(parsedSkeleton.id);
  55509. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  55510. }
  55511. }
  55512. }
  55513. }
  55514. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  55515. meshes.push(mesh);
  55516. log += "\n\tMesh " + mesh.toString(fullDetails);
  55517. }
  55518. }
  55519. // Connecting parents
  55520. var currentMesh;
  55521. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55522. currentMesh = scene.meshes[index];
  55523. if (currentMesh._waitingParentId) {
  55524. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  55525. currentMesh._waitingParentId = null;
  55526. }
  55527. }
  55528. // freeze and compute world matrix application
  55529. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55530. currentMesh = scene.meshes[index];
  55531. if (currentMesh._waitingFreezeWorldMatrix) {
  55532. currentMesh.freezeWorldMatrix();
  55533. currentMesh._waitingFreezeWorldMatrix = null;
  55534. }
  55535. else {
  55536. currentMesh.computeWorldMatrix(true);
  55537. }
  55538. }
  55539. }
  55540. // Particles
  55541. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  55542. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  55543. var parsedParticleSystem = parsedData.particleSystems[index];
  55544. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  55545. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  55546. }
  55547. }
  55548. }
  55549. return true;
  55550. }
  55551. catch (err) {
  55552. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  55553. if (onError) {
  55554. onError(msg, err);
  55555. }
  55556. else {
  55557. BABYLON.Tools.Log(msg);
  55558. throw err;
  55559. }
  55560. }
  55561. finally {
  55562. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55563. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55564. }
  55565. }
  55566. return false;
  55567. },
  55568. load: function (scene, data, rootUrl, onError) {
  55569. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  55570. // when SceneLoader.debugLogging = true (default), or exception encountered.
  55571. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  55572. // and avoid problems with multiple concurrent .babylon loads.
  55573. var log = "importScene has failed JSON parse";
  55574. try {
  55575. var parsedData = JSON.parse(data);
  55576. log = "";
  55577. // Scene
  55578. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  55579. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  55580. }
  55581. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  55582. scene.autoClear = parsedData.autoClear;
  55583. }
  55584. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  55585. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  55586. }
  55587. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  55588. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  55589. }
  55590. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  55591. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  55592. }
  55593. // Fog
  55594. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  55595. scene.fogMode = parsedData.fogMode;
  55596. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  55597. scene.fogStart = parsedData.fogStart;
  55598. scene.fogEnd = parsedData.fogEnd;
  55599. scene.fogDensity = parsedData.fogDensity;
  55600. log += "\tFog mode for scene: ";
  55601. switch (scene.fogMode) {
  55602. // getters not compiling, so using hardcoded
  55603. case 1:
  55604. log += "exp\n";
  55605. break;
  55606. case 2:
  55607. log += "exp2\n";
  55608. break;
  55609. case 3:
  55610. log += "linear\n";
  55611. break;
  55612. }
  55613. }
  55614. //Physics
  55615. if (parsedData.physicsEnabled) {
  55616. var physicsPlugin;
  55617. if (parsedData.physicsEngine === "cannon") {
  55618. physicsPlugin = new BABYLON.CannonJSPlugin();
  55619. }
  55620. else if (parsedData.physicsEngine === "oimo") {
  55621. physicsPlugin = new BABYLON.OimoJSPlugin();
  55622. }
  55623. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  55624. //else - default engine, which is currently oimo
  55625. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  55626. scene.enablePhysics(physicsGravity, physicsPlugin);
  55627. }
  55628. // Metadata
  55629. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  55630. scene.metadata = parsedData.metadata;
  55631. }
  55632. //collisions, if defined. otherwise, default is true
  55633. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  55634. scene.collisionsEnabled = parsedData.collisionsEnabled;
  55635. }
  55636. scene.workerCollisions = !!parsedData.workerCollisions;
  55637. var container = loadAssets(scene, data, rootUrl, onerror, true);
  55638. if (!container) {
  55639. return false;
  55640. }
  55641. if (parsedData.autoAnimate) {
  55642. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  55643. }
  55644. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  55645. scene.setActiveCameraByID(parsedData.activeCameraID);
  55646. }
  55647. // Environment texture
  55648. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  55649. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  55650. if (parsedData.createDefaultSkybox === true) {
  55651. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  55652. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  55653. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  55654. }
  55655. }
  55656. // Finish
  55657. return true;
  55658. }
  55659. catch (err) {
  55660. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  55661. if (onError) {
  55662. onError(msg, err);
  55663. }
  55664. else {
  55665. BABYLON.Tools.Log(msg);
  55666. throw err;
  55667. }
  55668. }
  55669. finally {
  55670. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55671. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55672. }
  55673. }
  55674. return false;
  55675. },
  55676. loadAssets: function (scene, data, rootUrl, onError) {
  55677. var container = loadAssets(scene, data, rootUrl, onerror);
  55678. return container;
  55679. }
  55680. });
  55681. })(BABYLON || (BABYLON = {}));
  55682. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  55683. var BABYLON;
  55684. (function (BABYLON) {
  55685. var FilesInput = /** @class */ (function () {
  55686. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  55687. this.onProcessFileCallback = function () { return true; };
  55688. this._engine = engine;
  55689. this._currentScene = scene;
  55690. this._sceneLoadedCallback = sceneLoadedCallback;
  55691. this._progressCallback = progressCallback;
  55692. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  55693. this._textureLoadingCallback = textureLoadingCallback;
  55694. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  55695. this._onReloadCallback = onReloadCallback;
  55696. this._errorCallback = errorCallback;
  55697. }
  55698. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  55699. var _this = this;
  55700. if (elementToMonitor) {
  55701. this._elementToMonitor = elementToMonitor;
  55702. this._dragEnterHandler = function (e) { _this.drag(e); };
  55703. this._dragOverHandler = function (e) { _this.drag(e); };
  55704. this._dropHandler = function (e) { _this.drop(e); };
  55705. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  55706. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  55707. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  55708. }
  55709. };
  55710. FilesInput.prototype.dispose = function () {
  55711. if (!this._elementToMonitor) {
  55712. return;
  55713. }
  55714. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  55715. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  55716. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  55717. };
  55718. FilesInput.prototype.renderFunction = function () {
  55719. if (this._additionalRenderLoopLogicCallback) {
  55720. this._additionalRenderLoopLogicCallback();
  55721. }
  55722. if (this._currentScene) {
  55723. if (this._textureLoadingCallback) {
  55724. var remaining = this._currentScene.getWaitingItemsCount();
  55725. if (remaining > 0) {
  55726. this._textureLoadingCallback(remaining);
  55727. }
  55728. }
  55729. this._currentScene.render();
  55730. }
  55731. };
  55732. FilesInput.prototype.drag = function (e) {
  55733. e.stopPropagation();
  55734. e.preventDefault();
  55735. };
  55736. FilesInput.prototype.drop = function (eventDrop) {
  55737. eventDrop.stopPropagation();
  55738. eventDrop.preventDefault();
  55739. this.loadFiles(eventDrop);
  55740. };
  55741. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  55742. var _this = this;
  55743. var reader = folder.createReader();
  55744. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  55745. reader.readEntries(function (entries) {
  55746. remaining.count += entries.length;
  55747. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  55748. var entry = entries_1[_i];
  55749. if (entry.isFile) {
  55750. entry.file(function (file) {
  55751. file.correctName = relativePath + file.name;
  55752. files.push(file);
  55753. if (--remaining.count === 0) {
  55754. callback();
  55755. }
  55756. });
  55757. }
  55758. else if (entry.isDirectory) {
  55759. _this._traverseFolder(entry, files, remaining, callback);
  55760. }
  55761. }
  55762. if (--remaining.count) {
  55763. callback();
  55764. }
  55765. });
  55766. };
  55767. FilesInput.prototype._processFiles = function (files) {
  55768. for (var i = 0; i < files.length; i++) {
  55769. var name = files[i].correctName.toLowerCase();
  55770. var extension = name.split('.').pop();
  55771. if (!this.onProcessFileCallback(files[i], name, extension)) {
  55772. continue;
  55773. }
  55774. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  55775. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  55776. this._sceneFileToLoad = files[i];
  55777. }
  55778. else {
  55779. FilesInput.FilesToLoad[name] = files[i];
  55780. }
  55781. }
  55782. };
  55783. FilesInput.prototype.loadFiles = function (event) {
  55784. var _this = this;
  55785. if (this._startingProcessingFilesCallback)
  55786. this._startingProcessingFilesCallback();
  55787. // Handling data transfer via drag'n'drop
  55788. if (event && event.dataTransfer && event.dataTransfer.files) {
  55789. this._filesToLoad = event.dataTransfer.files;
  55790. }
  55791. // Handling files from input files
  55792. if (event && event.target && event.target.files) {
  55793. this._filesToLoad = event.target.files;
  55794. }
  55795. if (this._filesToLoad && this._filesToLoad.length > 0) {
  55796. var files_1 = new Array();
  55797. var folders = [];
  55798. var items = event.dataTransfer ? event.dataTransfer.items : null;
  55799. for (var i = 0; i < this._filesToLoad.length; i++) {
  55800. var fileToLoad = this._filesToLoad[i];
  55801. var name_1 = fileToLoad.name.toLowerCase();
  55802. var entry = void 0;
  55803. fileToLoad.correctName = name_1;
  55804. if (items) {
  55805. var item = items[i];
  55806. if (item.getAsEntry) {
  55807. entry = item.getAsEntry();
  55808. }
  55809. else if (item.webkitGetAsEntry) {
  55810. entry = item.webkitGetAsEntry();
  55811. }
  55812. }
  55813. if (!entry) {
  55814. files_1.push(fileToLoad);
  55815. }
  55816. else {
  55817. if (entry.isDirectory) {
  55818. folders.push(entry);
  55819. }
  55820. else {
  55821. files_1.push(fileToLoad);
  55822. }
  55823. }
  55824. }
  55825. if (folders.length === 0) {
  55826. this._processFiles(files_1);
  55827. this._processReload();
  55828. }
  55829. else {
  55830. var remaining = { count: folders.length };
  55831. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  55832. var folder = folders_1[_i];
  55833. this._traverseFolder(folder, files_1, remaining, function () {
  55834. _this._processFiles(files_1);
  55835. if (remaining.count === 0) {
  55836. _this._processReload();
  55837. }
  55838. });
  55839. }
  55840. }
  55841. }
  55842. };
  55843. FilesInput.prototype._processReload = function () {
  55844. if (this._onReloadCallback) {
  55845. this._onReloadCallback(this._sceneFileToLoad);
  55846. }
  55847. else {
  55848. this.reload();
  55849. }
  55850. };
  55851. FilesInput.prototype.reload = function () {
  55852. var _this = this;
  55853. // If a scene file has been provided
  55854. if (this._sceneFileToLoad) {
  55855. if (this._currentScene) {
  55856. if (BABYLON.Tools.errorsCount > 0) {
  55857. BABYLON.Tools.ClearLogCache();
  55858. }
  55859. this._engine.stopRenderLoop();
  55860. this._currentScene.dispose();
  55861. }
  55862. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  55863. _this._currentScene = newScene;
  55864. if (_this._sceneLoadedCallback) {
  55865. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  55866. }
  55867. // Wait for textures and shaders to be ready
  55868. _this._currentScene.executeWhenReady(function () {
  55869. _this._engine.runRenderLoop(function () {
  55870. _this.renderFunction();
  55871. });
  55872. });
  55873. }, function (progress) {
  55874. if (_this._progressCallback) {
  55875. _this._progressCallback(progress);
  55876. }
  55877. }, function (scene, message) {
  55878. _this._currentScene = scene;
  55879. if (_this._errorCallback) {
  55880. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  55881. }
  55882. });
  55883. }
  55884. else {
  55885. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  55886. }
  55887. };
  55888. FilesInput.FilesToLoad = {};
  55889. return FilesInput;
  55890. }());
  55891. BABYLON.FilesInput = FilesInput;
  55892. })(BABYLON || (BABYLON = {}));
  55893. //# sourceMappingURL=babylon.filesInput.js.map
  55894. var BABYLON;
  55895. (function (BABYLON) {
  55896. /**
  55897. * This class implement a typical dictionary using a string as key and the generic type T as value.
  55898. * The underlying implementation relies on an associative array to ensure the best performances.
  55899. * The value can be anything including 'null' but except 'undefined'
  55900. */
  55901. var StringDictionary = /** @class */ (function () {
  55902. function StringDictionary() {
  55903. this._count = 0;
  55904. this._data = {};
  55905. }
  55906. /**
  55907. * This will clear this dictionary and copy the content from the 'source' one.
  55908. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  55909. * @param source the dictionary to take the content from and copy to this dictionary
  55910. */
  55911. StringDictionary.prototype.copyFrom = function (source) {
  55912. var _this = this;
  55913. this.clear();
  55914. source.forEach(function (t, v) { return _this.add(t, v); });
  55915. };
  55916. /**
  55917. * Get a value based from its key
  55918. * @param key the given key to get the matching value from
  55919. * @return the value if found, otherwise undefined is returned
  55920. */
  55921. StringDictionary.prototype.get = function (key) {
  55922. var val = this._data[key];
  55923. if (val !== undefined) {
  55924. return val;
  55925. }
  55926. return undefined;
  55927. };
  55928. /**
  55929. * Get a value from its key or add it if it doesn't exist.
  55930. * This method will ensure you that a given key/data will be present in the dictionary.
  55931. * @param key the given key to get the matching value from
  55932. * @param factory the factory that will create the value if the key is not present in the dictionary.
  55933. * The factory will only be invoked if there's no data for the given key.
  55934. * @return the value corresponding to the key.
  55935. */
  55936. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  55937. var val = this.get(key);
  55938. if (val !== undefined) {
  55939. return val;
  55940. }
  55941. val = factory(key);
  55942. if (val) {
  55943. this.add(key, val);
  55944. }
  55945. return val;
  55946. };
  55947. /**
  55948. * Get a value from its key if present in the dictionary otherwise add it
  55949. * @param key the key to get the value from
  55950. * @param val if there's no such key/value pair in the dictionary add it with this value
  55951. * @return the value corresponding to the key
  55952. */
  55953. StringDictionary.prototype.getOrAdd = function (key, val) {
  55954. var curVal = this.get(key);
  55955. if (curVal !== undefined) {
  55956. return curVal;
  55957. }
  55958. this.add(key, val);
  55959. return val;
  55960. };
  55961. /**
  55962. * Check if there's a given key in the dictionary
  55963. * @param key the key to check for
  55964. * @return true if the key is present, false otherwise
  55965. */
  55966. StringDictionary.prototype.contains = function (key) {
  55967. return this._data[key] !== undefined;
  55968. };
  55969. /**
  55970. * Add a new key and its corresponding value
  55971. * @param key the key to add
  55972. * @param value the value corresponding to the key
  55973. * @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
  55974. */
  55975. StringDictionary.prototype.add = function (key, value) {
  55976. if (this._data[key] !== undefined) {
  55977. return false;
  55978. }
  55979. this._data[key] = value;
  55980. ++this._count;
  55981. return true;
  55982. };
  55983. StringDictionary.prototype.set = function (key, value) {
  55984. if (this._data[key] === undefined) {
  55985. return false;
  55986. }
  55987. this._data[key] = value;
  55988. return true;
  55989. };
  55990. /**
  55991. * Get the element of the given key and remove it from the dictionary
  55992. * @param key
  55993. */
  55994. StringDictionary.prototype.getAndRemove = function (key) {
  55995. var val = this.get(key);
  55996. if (val !== undefined) {
  55997. delete this._data[key];
  55998. --this._count;
  55999. return val;
  56000. }
  56001. return null;
  56002. };
  56003. /**
  56004. * Remove a key/value from the dictionary.
  56005. * @param key the key to remove
  56006. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  56007. */
  56008. StringDictionary.prototype.remove = function (key) {
  56009. if (this.contains(key)) {
  56010. delete this._data[key];
  56011. --this._count;
  56012. return true;
  56013. }
  56014. return false;
  56015. };
  56016. /**
  56017. * Clear the whole content of the dictionary
  56018. */
  56019. StringDictionary.prototype.clear = function () {
  56020. this._data = {};
  56021. this._count = 0;
  56022. };
  56023. Object.defineProperty(StringDictionary.prototype, "count", {
  56024. get: function () {
  56025. return this._count;
  56026. },
  56027. enumerable: true,
  56028. configurable: true
  56029. });
  56030. /**
  56031. * Execute a callback on each key/val of the dictionary.
  56032. * Note that you can remove any element in this dictionary in the callback implementation
  56033. * @param callback the callback to execute on a given key/value pair
  56034. */
  56035. StringDictionary.prototype.forEach = function (callback) {
  56036. for (var cur in this._data) {
  56037. var val = this._data[cur];
  56038. callback(cur, val);
  56039. }
  56040. };
  56041. /**
  56042. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  56043. * If the callback returns null or undefined the method will iterate to the next key/value pair
  56044. * Note that you can remove any element in this dictionary in the callback implementation
  56045. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  56046. */
  56047. StringDictionary.prototype.first = function (callback) {
  56048. for (var cur in this._data) {
  56049. var val = this._data[cur];
  56050. var res = callback(cur, val);
  56051. if (res) {
  56052. return res;
  56053. }
  56054. }
  56055. return null;
  56056. };
  56057. return StringDictionary;
  56058. }());
  56059. BABYLON.StringDictionary = StringDictionary;
  56060. })(BABYLON || (BABYLON = {}));
  56061. //# sourceMappingURL=babylon.stringDictionary.js.map
  56062. var BABYLON;
  56063. (function (BABYLON) {
  56064. var Tags = /** @class */ (function () {
  56065. function Tags() {
  56066. }
  56067. Tags.EnableFor = function (obj) {
  56068. obj._tags = obj._tags || {};
  56069. obj.hasTags = function () {
  56070. return Tags.HasTags(obj);
  56071. };
  56072. obj.addTags = function (tagsString) {
  56073. return Tags.AddTagsTo(obj, tagsString);
  56074. };
  56075. obj.removeTags = function (tagsString) {
  56076. return Tags.RemoveTagsFrom(obj, tagsString);
  56077. };
  56078. obj.matchesTagsQuery = function (tagsQuery) {
  56079. return Tags.MatchesQuery(obj, tagsQuery);
  56080. };
  56081. };
  56082. Tags.DisableFor = function (obj) {
  56083. delete obj._tags;
  56084. delete obj.hasTags;
  56085. delete obj.addTags;
  56086. delete obj.removeTags;
  56087. delete obj.matchesTagsQuery;
  56088. };
  56089. Tags.HasTags = function (obj) {
  56090. if (!obj._tags) {
  56091. return false;
  56092. }
  56093. return !BABYLON.Tools.IsEmpty(obj._tags);
  56094. };
  56095. Tags.GetTags = function (obj, asString) {
  56096. if (asString === void 0) { asString = true; }
  56097. if (!obj._tags) {
  56098. return null;
  56099. }
  56100. if (asString) {
  56101. var tagsArray = [];
  56102. for (var tag in obj._tags) {
  56103. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  56104. tagsArray.push(tag);
  56105. }
  56106. }
  56107. return tagsArray.join(" ");
  56108. }
  56109. else {
  56110. return obj._tags;
  56111. }
  56112. };
  56113. // the tags 'true' and 'false' are reserved and cannot be used as tags
  56114. // a tag cannot start with '||', '&&', and '!'
  56115. // it cannot contain whitespaces
  56116. Tags.AddTagsTo = function (obj, tagsString) {
  56117. if (!tagsString) {
  56118. return;
  56119. }
  56120. if (typeof tagsString !== "string") {
  56121. return;
  56122. }
  56123. var tags = tagsString.split(" ");
  56124. tags.forEach(function (tag, index, array) {
  56125. Tags._AddTagTo(obj, tag);
  56126. });
  56127. };
  56128. Tags._AddTagTo = function (obj, tag) {
  56129. tag = tag.trim();
  56130. if (tag === "" || tag === "true" || tag === "false") {
  56131. return;
  56132. }
  56133. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  56134. return;
  56135. }
  56136. Tags.EnableFor(obj);
  56137. obj._tags[tag] = true;
  56138. };
  56139. Tags.RemoveTagsFrom = function (obj, tagsString) {
  56140. if (!Tags.HasTags(obj)) {
  56141. return;
  56142. }
  56143. var tags = tagsString.split(" ");
  56144. for (var t in tags) {
  56145. Tags._RemoveTagFrom(obj, tags[t]);
  56146. }
  56147. };
  56148. Tags._RemoveTagFrom = function (obj, tag) {
  56149. delete obj._tags[tag];
  56150. };
  56151. Tags.MatchesQuery = function (obj, tagsQuery) {
  56152. if (tagsQuery === undefined) {
  56153. return true;
  56154. }
  56155. if (tagsQuery === "") {
  56156. return Tags.HasTags(obj);
  56157. }
  56158. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  56159. };
  56160. return Tags;
  56161. }());
  56162. BABYLON.Tags = Tags;
  56163. })(BABYLON || (BABYLON = {}));
  56164. //# sourceMappingURL=babylon.tags.js.map
  56165. var BABYLON;
  56166. (function (BABYLON) {
  56167. var AndOrNotEvaluator = /** @class */ (function () {
  56168. function AndOrNotEvaluator() {
  56169. }
  56170. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  56171. if (!query.match(/\([^\(\)]*\)/g)) {
  56172. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  56173. }
  56174. else {
  56175. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  56176. // remove parenthesis
  56177. r = r.slice(1, r.length - 1);
  56178. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  56179. });
  56180. }
  56181. if (query === "true") {
  56182. return true;
  56183. }
  56184. if (query === "false") {
  56185. return false;
  56186. }
  56187. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  56188. };
  56189. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  56190. evaluateCallback = evaluateCallback || (function (r) {
  56191. return r === "true" ? true : false;
  56192. });
  56193. var result;
  56194. var or = parenthesisContent.split("||");
  56195. for (var i in or) {
  56196. if (or.hasOwnProperty(i)) {
  56197. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  56198. var and = ori.split("&&");
  56199. if (and.length > 1) {
  56200. for (var j = 0; j < and.length; ++j) {
  56201. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  56202. if (andj !== "true" && andj !== "false") {
  56203. if (andj[0] === "!") {
  56204. result = !evaluateCallback(andj.substring(1));
  56205. }
  56206. else {
  56207. result = evaluateCallback(andj);
  56208. }
  56209. }
  56210. else {
  56211. result = andj === "true" ? true : false;
  56212. }
  56213. if (!result) {
  56214. ori = "false";
  56215. break;
  56216. }
  56217. }
  56218. }
  56219. if (result || ori === "true") {
  56220. result = true;
  56221. break;
  56222. }
  56223. // result equals false (or undefined)
  56224. if (ori !== "true" && ori !== "false") {
  56225. if (ori[0] === "!") {
  56226. result = !evaluateCallback(ori.substring(1));
  56227. }
  56228. else {
  56229. result = evaluateCallback(ori);
  56230. }
  56231. }
  56232. else {
  56233. result = ori === "true" ? true : false;
  56234. }
  56235. }
  56236. }
  56237. // the whole parenthesis scope is replaced by 'true' or 'false'
  56238. return result ? "true" : "false";
  56239. };
  56240. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  56241. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  56242. // remove whitespaces
  56243. r = r.replace(/[\s]/g, function () { return ""; });
  56244. return r.length % 2 ? "!" : "";
  56245. });
  56246. booleanString = booleanString.trim();
  56247. if (booleanString === "!true") {
  56248. booleanString = "false";
  56249. }
  56250. else if (booleanString === "!false") {
  56251. booleanString = "true";
  56252. }
  56253. return booleanString;
  56254. };
  56255. return AndOrNotEvaluator;
  56256. }());
  56257. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  56258. })(BABYLON || (BABYLON = {}));
  56259. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  56260. var BABYLON;
  56261. (function (BABYLON) {
  56262. var Database = /** @class */ (function () {
  56263. function Database(urlToScene, callbackManifestChecked) {
  56264. // Handling various flavors of prefixed version of IndexedDB
  56265. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  56266. this.callbackManifestChecked = callbackManifestChecked;
  56267. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  56268. this.db = null;
  56269. this._enableSceneOffline = false;
  56270. this._enableTexturesOffline = false;
  56271. this.manifestVersionFound = 0;
  56272. this.mustUpdateRessources = false;
  56273. this.hasReachedQuota = false;
  56274. if (!Database.IDBStorageEnabled) {
  56275. this.callbackManifestChecked(true);
  56276. }
  56277. else {
  56278. this.checkManifestFile();
  56279. }
  56280. }
  56281. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  56282. get: function () {
  56283. return this._enableSceneOffline;
  56284. },
  56285. enumerable: true,
  56286. configurable: true
  56287. });
  56288. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  56289. get: function () {
  56290. return this._enableTexturesOffline;
  56291. },
  56292. enumerable: true,
  56293. configurable: true
  56294. });
  56295. Database.prototype.checkManifestFile = function () {
  56296. var _this = this;
  56297. var noManifestFile = function () {
  56298. _this._enableSceneOffline = false;
  56299. _this._enableTexturesOffline = false;
  56300. _this.callbackManifestChecked(false);
  56301. };
  56302. var timeStampUsed = false;
  56303. var manifestURL = this.currentSceneUrl + ".manifest";
  56304. var xhr = new XMLHttpRequest();
  56305. if (navigator.onLine) {
  56306. // Adding a timestamp to by-pass browsers' cache
  56307. timeStampUsed = true;
  56308. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  56309. }
  56310. xhr.open("GET", manifestURL, true);
  56311. xhr.addEventListener("load", function () {
  56312. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  56313. try {
  56314. var manifestFile = JSON.parse(xhr.response);
  56315. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  56316. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  56317. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  56318. _this.manifestVersionFound = manifestFile.version;
  56319. }
  56320. if (_this.callbackManifestChecked) {
  56321. _this.callbackManifestChecked(true);
  56322. }
  56323. }
  56324. catch (ex) {
  56325. noManifestFile();
  56326. }
  56327. }
  56328. else {
  56329. noManifestFile();
  56330. }
  56331. }, false);
  56332. xhr.addEventListener("error", function (event) {
  56333. if (timeStampUsed) {
  56334. timeStampUsed = false;
  56335. // Let's retry without the timeStamp
  56336. // It could fail when coupled with HTML5 Offline API
  56337. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  56338. xhr.open("GET", retryManifestURL, true);
  56339. xhr.send();
  56340. }
  56341. else {
  56342. noManifestFile();
  56343. }
  56344. }, false);
  56345. try {
  56346. xhr.send();
  56347. }
  56348. catch (ex) {
  56349. BABYLON.Tools.Error("Error on XHR send request.");
  56350. this.callbackManifestChecked(false);
  56351. }
  56352. };
  56353. Database.prototype.openAsync = function (successCallback, errorCallback) {
  56354. var _this = this;
  56355. var handleError = function () {
  56356. _this.isSupported = false;
  56357. if (errorCallback)
  56358. errorCallback();
  56359. };
  56360. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  56361. // Your browser doesn't support IndexedDB
  56362. this.isSupported = false;
  56363. if (errorCallback)
  56364. errorCallback();
  56365. }
  56366. else {
  56367. // If the DB hasn't been opened or created yet
  56368. if (!this.db) {
  56369. this.hasReachedQuota = false;
  56370. this.isSupported = true;
  56371. var request = this.idbFactory.open("babylonjs", 1);
  56372. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  56373. request.onerror = function (event) {
  56374. handleError();
  56375. };
  56376. // executes when a version change transaction cannot complete due to other active transactions
  56377. request.onblocked = function (event) {
  56378. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  56379. handleError();
  56380. };
  56381. // DB has been opened successfully
  56382. request.onsuccess = function (event) {
  56383. _this.db = request.result;
  56384. successCallback();
  56385. };
  56386. // Initialization of the DB. Creating Scenes & Textures stores
  56387. request.onupgradeneeded = function (event) {
  56388. _this.db = (event.target).result;
  56389. if (_this.db) {
  56390. try {
  56391. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  56392. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  56393. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  56394. }
  56395. catch (ex) {
  56396. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  56397. handleError();
  56398. }
  56399. }
  56400. };
  56401. }
  56402. else {
  56403. if (successCallback)
  56404. successCallback();
  56405. }
  56406. }
  56407. };
  56408. Database.prototype.loadImageFromDB = function (url, image) {
  56409. var _this = this;
  56410. var completeURL = Database.ReturnFullUrlLocation(url);
  56411. var saveAndLoadImage = function () {
  56412. if (!_this.hasReachedQuota && _this.db !== null) {
  56413. // the texture is not yet in the DB, let's try to save it
  56414. _this._saveImageIntoDBAsync(completeURL, image);
  56415. }
  56416. else {
  56417. image.src = url;
  56418. }
  56419. };
  56420. if (!this.mustUpdateRessources) {
  56421. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  56422. }
  56423. else {
  56424. saveAndLoadImage();
  56425. }
  56426. };
  56427. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  56428. if (this.isSupported && this.db !== null) {
  56429. var texture;
  56430. var transaction = this.db.transaction(["textures"]);
  56431. transaction.onabort = function (event) {
  56432. image.src = url;
  56433. };
  56434. transaction.oncomplete = function (event) {
  56435. var blobTextureURL;
  56436. if (texture) {
  56437. var URL = window.URL || window.webkitURL;
  56438. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  56439. image.onerror = function () {
  56440. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  56441. image.src = url;
  56442. };
  56443. image.src = blobTextureURL;
  56444. }
  56445. else {
  56446. notInDBCallback();
  56447. }
  56448. };
  56449. var getRequest = transaction.objectStore("textures").get(url);
  56450. getRequest.onsuccess = function (event) {
  56451. texture = (event.target).result;
  56452. };
  56453. getRequest.onerror = function (event) {
  56454. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  56455. image.src = url;
  56456. };
  56457. }
  56458. else {
  56459. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56460. image.src = url;
  56461. }
  56462. };
  56463. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  56464. var _this = this;
  56465. if (this.isSupported) {
  56466. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  56467. var generateBlobUrl = function () {
  56468. var blobTextureURL;
  56469. if (blob) {
  56470. var URL = window.URL || window.webkitURL;
  56471. try {
  56472. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  56473. }
  56474. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  56475. catch (ex) {
  56476. blobTextureURL = URL.createObjectURL(blob);
  56477. }
  56478. }
  56479. if (blobTextureURL) {
  56480. image.src = blobTextureURL;
  56481. }
  56482. };
  56483. if (Database.IsUASupportingBlobStorage) {
  56484. var xhr = new XMLHttpRequest(), blob;
  56485. xhr.open("GET", url, true);
  56486. xhr.responseType = "blob";
  56487. xhr.addEventListener("load", function () {
  56488. if (xhr.status === 200 && _this.db) {
  56489. // Blob as response (XHR2)
  56490. blob = xhr.response;
  56491. var transaction = _this.db.transaction(["textures"], "readwrite");
  56492. // the transaction could abort because of a QuotaExceededError error
  56493. transaction.onabort = function (event) {
  56494. try {
  56495. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  56496. var srcElement = (event.srcElement || event.target);
  56497. var error = srcElement.error;
  56498. if (error && error.name === "QuotaExceededError") {
  56499. _this.hasReachedQuota = true;
  56500. }
  56501. }
  56502. catch (ex) { }
  56503. generateBlobUrl();
  56504. };
  56505. transaction.oncomplete = function (event) {
  56506. generateBlobUrl();
  56507. };
  56508. var newTexture = { textureUrl: url, data: blob };
  56509. try {
  56510. // Put the blob into the dabase
  56511. var addRequest = transaction.objectStore("textures").put(newTexture);
  56512. addRequest.onsuccess = function (event) {
  56513. };
  56514. addRequest.onerror = function (event) {
  56515. generateBlobUrl();
  56516. };
  56517. }
  56518. catch (ex) {
  56519. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  56520. if (ex.code === 25) {
  56521. Database.IsUASupportingBlobStorage = false;
  56522. }
  56523. image.src = url;
  56524. }
  56525. }
  56526. else {
  56527. image.src = url;
  56528. }
  56529. }, false);
  56530. xhr.addEventListener("error", function (event) {
  56531. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  56532. image.src = url;
  56533. }, false);
  56534. xhr.send();
  56535. }
  56536. else {
  56537. image.src = url;
  56538. }
  56539. }
  56540. else {
  56541. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56542. image.src = url;
  56543. }
  56544. };
  56545. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  56546. var _this = this;
  56547. var updateVersion = function () {
  56548. // the version is not yet in the DB or we need to update it
  56549. _this._saveVersionIntoDBAsync(url, versionLoaded);
  56550. };
  56551. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  56552. };
  56553. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  56554. var _this = this;
  56555. if (this.isSupported && this.db) {
  56556. var version;
  56557. try {
  56558. var transaction = this.db.transaction(["versions"]);
  56559. transaction.oncomplete = function (event) {
  56560. if (version) {
  56561. // If the version in the JSON file is > than the version in DB
  56562. if (_this.manifestVersionFound > version.data) {
  56563. _this.mustUpdateRessources = true;
  56564. updateInDBCallback();
  56565. }
  56566. else {
  56567. callback(version.data);
  56568. }
  56569. }
  56570. else {
  56571. _this.mustUpdateRessources = true;
  56572. updateInDBCallback();
  56573. }
  56574. };
  56575. transaction.onabort = function (event) {
  56576. callback(-1);
  56577. };
  56578. var getRequest = transaction.objectStore("versions").get(url);
  56579. getRequest.onsuccess = function (event) {
  56580. version = (event.target).result;
  56581. };
  56582. getRequest.onerror = function (event) {
  56583. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  56584. callback(-1);
  56585. };
  56586. }
  56587. catch (ex) {
  56588. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  56589. callback(-1);
  56590. }
  56591. }
  56592. else {
  56593. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56594. callback(-1);
  56595. }
  56596. };
  56597. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  56598. var _this = this;
  56599. if (this.isSupported && !this.hasReachedQuota && this.db) {
  56600. try {
  56601. // Open a transaction to the database
  56602. var transaction = this.db.transaction(["versions"], "readwrite");
  56603. // the transaction could abort because of a QuotaExceededError error
  56604. transaction.onabort = function (event) {
  56605. try {
  56606. var error = event.srcElement['error'];
  56607. if (error && error.name === "QuotaExceededError") {
  56608. _this.hasReachedQuota = true;
  56609. }
  56610. }
  56611. catch (ex) { }
  56612. callback(-1);
  56613. };
  56614. transaction.oncomplete = function (event) {
  56615. callback(_this.manifestVersionFound);
  56616. };
  56617. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  56618. // Put the scene into the database
  56619. var addRequest = transaction.objectStore("versions").put(newVersion);
  56620. addRequest.onsuccess = function (event) {
  56621. };
  56622. addRequest.onerror = function (event) {
  56623. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  56624. };
  56625. }
  56626. catch (ex) {
  56627. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  56628. callback(-1);
  56629. }
  56630. }
  56631. else {
  56632. callback(-1);
  56633. }
  56634. };
  56635. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  56636. var _this = this;
  56637. var completeUrl = Database.ReturnFullUrlLocation(url);
  56638. var saveAndLoadFile = function () {
  56639. // the scene is not yet in the DB, let's try to save it
  56640. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  56641. };
  56642. this._checkVersionFromDB(completeUrl, function (version) {
  56643. if (version !== -1) {
  56644. if (!_this.mustUpdateRessources) {
  56645. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  56646. }
  56647. else {
  56648. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  56649. }
  56650. }
  56651. else {
  56652. if (errorCallback) {
  56653. errorCallback();
  56654. }
  56655. }
  56656. });
  56657. };
  56658. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  56659. if (this.isSupported && this.db) {
  56660. var targetStore;
  56661. if (url.indexOf(".babylon") !== -1) {
  56662. targetStore = "scenes";
  56663. }
  56664. else {
  56665. targetStore = "textures";
  56666. }
  56667. var file;
  56668. var transaction = this.db.transaction([targetStore]);
  56669. transaction.oncomplete = function (event) {
  56670. if (file) {
  56671. callback(file.data);
  56672. }
  56673. else {
  56674. notInDBCallback();
  56675. }
  56676. };
  56677. transaction.onabort = function (event) {
  56678. notInDBCallback();
  56679. };
  56680. var getRequest = transaction.objectStore(targetStore).get(url);
  56681. getRequest.onsuccess = function (event) {
  56682. file = (event.target).result;
  56683. };
  56684. getRequest.onerror = function (event) {
  56685. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  56686. notInDBCallback();
  56687. };
  56688. }
  56689. else {
  56690. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56691. callback();
  56692. }
  56693. };
  56694. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  56695. var _this = this;
  56696. if (this.isSupported) {
  56697. var targetStore;
  56698. if (url.indexOf(".babylon") !== -1) {
  56699. targetStore = "scenes";
  56700. }
  56701. else {
  56702. targetStore = "textures";
  56703. }
  56704. // Create XHR
  56705. var xhr = new XMLHttpRequest();
  56706. var fileData;
  56707. xhr.open("GET", url, true);
  56708. if (useArrayBuffer) {
  56709. xhr.responseType = "arraybuffer";
  56710. }
  56711. if (progressCallback) {
  56712. xhr.onprogress = progressCallback;
  56713. }
  56714. xhr.addEventListener("load", function () {
  56715. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  56716. // Blob as response (XHR2)
  56717. //fileData = xhr.responseText;
  56718. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  56719. if (!_this.hasReachedQuota && _this.db) {
  56720. // Open a transaction to the database
  56721. var transaction = _this.db.transaction([targetStore], "readwrite");
  56722. // the transaction could abort because of a QuotaExceededError error
  56723. transaction.onabort = function (event) {
  56724. try {
  56725. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  56726. var error = event.srcElement['error'];
  56727. if (error && error.name === "QuotaExceededError") {
  56728. _this.hasReachedQuota = true;
  56729. }
  56730. }
  56731. catch (ex) { }
  56732. callback(fileData);
  56733. };
  56734. transaction.oncomplete = function (event) {
  56735. callback(fileData);
  56736. };
  56737. var newFile;
  56738. if (targetStore === "scenes") {
  56739. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  56740. }
  56741. else {
  56742. newFile = { textureUrl: url, data: fileData };
  56743. }
  56744. try {
  56745. // Put the scene into the database
  56746. var addRequest = transaction.objectStore(targetStore).put(newFile);
  56747. addRequest.onsuccess = function (event) {
  56748. };
  56749. addRequest.onerror = function (event) {
  56750. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  56751. };
  56752. }
  56753. catch (ex) {
  56754. callback(fileData);
  56755. }
  56756. }
  56757. else {
  56758. callback(fileData);
  56759. }
  56760. }
  56761. else {
  56762. callback();
  56763. }
  56764. }, false);
  56765. xhr.addEventListener("error", function (event) {
  56766. BABYLON.Tools.Error("error on XHR request.");
  56767. callback();
  56768. }, false);
  56769. xhr.send();
  56770. }
  56771. else {
  56772. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56773. callback();
  56774. }
  56775. };
  56776. Database.IsUASupportingBlobStorage = true;
  56777. Database.IDBStorageEnabled = true;
  56778. Database.parseURL = function (url) {
  56779. var a = document.createElement('a');
  56780. a.href = url;
  56781. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  56782. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  56783. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  56784. return absLocation;
  56785. };
  56786. Database.ReturnFullUrlLocation = function (url) {
  56787. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  56788. return (Database.parseURL(window.location.href) + url);
  56789. }
  56790. else {
  56791. return url;
  56792. }
  56793. };
  56794. return Database;
  56795. }());
  56796. BABYLON.Database = Database;
  56797. })(BABYLON || (BABYLON = {}));
  56798. //# sourceMappingURL=babylon.database.js.map
  56799. var BABYLON;
  56800. (function (BABYLON) {
  56801. var FresnelParameters = /** @class */ (function () {
  56802. function FresnelParameters() {
  56803. this._isEnabled = true;
  56804. this.leftColor = BABYLON.Color3.White();
  56805. this.rightColor = BABYLON.Color3.Black();
  56806. this.bias = 0;
  56807. this.power = 1;
  56808. }
  56809. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  56810. get: function () {
  56811. return this._isEnabled;
  56812. },
  56813. set: function (value) {
  56814. if (this._isEnabled === value) {
  56815. return;
  56816. }
  56817. this._isEnabled = value;
  56818. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  56819. },
  56820. enumerable: true,
  56821. configurable: true
  56822. });
  56823. FresnelParameters.prototype.clone = function () {
  56824. var newFresnelParameters = new FresnelParameters();
  56825. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  56826. return newFresnelParameters;
  56827. };
  56828. FresnelParameters.prototype.serialize = function () {
  56829. var serializationObject = {};
  56830. serializationObject.isEnabled = this.isEnabled;
  56831. serializationObject.leftColor = this.leftColor;
  56832. serializationObject.rightColor = this.rightColor;
  56833. serializationObject.bias = this.bias;
  56834. serializationObject.power = this.power;
  56835. return serializationObject;
  56836. };
  56837. FresnelParameters.Parse = function (parsedFresnelParameters) {
  56838. var fresnelParameters = new FresnelParameters();
  56839. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  56840. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  56841. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  56842. fresnelParameters.bias = parsedFresnelParameters.bias;
  56843. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  56844. return fresnelParameters;
  56845. };
  56846. return FresnelParameters;
  56847. }());
  56848. BABYLON.FresnelParameters = FresnelParameters;
  56849. })(BABYLON || (BABYLON = {}));
  56850. //# sourceMappingURL=babylon.fresnelParameters.js.map
  56851. var BABYLON;
  56852. (function (BABYLON) {
  56853. var MultiMaterial = /** @class */ (function (_super) {
  56854. __extends(MultiMaterial, _super);
  56855. function MultiMaterial(name, scene) {
  56856. var _this = _super.call(this, name, scene, true) || this;
  56857. scene.multiMaterials.push(_this);
  56858. _this.subMaterials = new Array();
  56859. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  56860. return _this;
  56861. }
  56862. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  56863. get: function () {
  56864. return this._subMaterials;
  56865. },
  56866. set: function (value) {
  56867. this._subMaterials = value;
  56868. this._hookArray(value);
  56869. },
  56870. enumerable: true,
  56871. configurable: true
  56872. });
  56873. MultiMaterial.prototype._hookArray = function (array) {
  56874. var _this = this;
  56875. var oldPush = array.push;
  56876. array.push = function () {
  56877. var items = [];
  56878. for (var _i = 0; _i < arguments.length; _i++) {
  56879. items[_i] = arguments[_i];
  56880. }
  56881. var result = oldPush.apply(array, items);
  56882. _this._markAllSubMeshesAsTexturesDirty();
  56883. return result;
  56884. };
  56885. var oldSplice = array.splice;
  56886. array.splice = function (index, deleteCount) {
  56887. var deleted = oldSplice.apply(array, [index, deleteCount]);
  56888. _this._markAllSubMeshesAsTexturesDirty();
  56889. return deleted;
  56890. };
  56891. };
  56892. // Properties
  56893. MultiMaterial.prototype.getSubMaterial = function (index) {
  56894. if (index < 0 || index >= this.subMaterials.length) {
  56895. return this.getScene().defaultMaterial;
  56896. }
  56897. return this.subMaterials[index];
  56898. };
  56899. MultiMaterial.prototype.getActiveTextures = function () {
  56900. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  56901. if (subMaterial) {
  56902. return subMaterial.getActiveTextures();
  56903. }
  56904. else {
  56905. return [];
  56906. }
  56907. }));
  56908. var _a;
  56909. };
  56910. // Methods
  56911. MultiMaterial.prototype.getClassName = function () {
  56912. return "MultiMaterial";
  56913. };
  56914. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  56915. for (var index = 0; index < this.subMaterials.length; index++) {
  56916. var subMaterial = this.subMaterials[index];
  56917. if (subMaterial) {
  56918. if (subMaterial.storeEffectOnSubMeshes) {
  56919. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  56920. return false;
  56921. }
  56922. continue;
  56923. }
  56924. if (!subMaterial.isReady(mesh)) {
  56925. return false;
  56926. }
  56927. }
  56928. }
  56929. return true;
  56930. };
  56931. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  56932. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  56933. for (var index = 0; index < this.subMaterials.length; index++) {
  56934. var subMaterial = null;
  56935. var current = this.subMaterials[index];
  56936. if (cloneChildren && current) {
  56937. subMaterial = current.clone(name + "-" + current.name);
  56938. }
  56939. else {
  56940. subMaterial = this.subMaterials[index];
  56941. }
  56942. newMultiMaterial.subMaterials.push(subMaterial);
  56943. }
  56944. return newMultiMaterial;
  56945. };
  56946. MultiMaterial.prototype.serialize = function () {
  56947. var serializationObject = {};
  56948. serializationObject.name = this.name;
  56949. serializationObject.id = this.id;
  56950. if (BABYLON.Tags) {
  56951. serializationObject.tags = BABYLON.Tags.GetTags(this);
  56952. }
  56953. serializationObject.materials = [];
  56954. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  56955. var subMat = this.subMaterials[matIndex];
  56956. if (subMat) {
  56957. serializationObject.materials.push(subMat.id);
  56958. }
  56959. else {
  56960. serializationObject.materials.push(null);
  56961. }
  56962. }
  56963. return serializationObject;
  56964. };
  56965. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  56966. var scene = this.getScene();
  56967. if (!scene) {
  56968. return;
  56969. }
  56970. var index = scene.multiMaterials.indexOf(this);
  56971. if (index >= 0) {
  56972. scene.multiMaterials.splice(index, 1);
  56973. }
  56974. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  56975. };
  56976. return MultiMaterial;
  56977. }(BABYLON.Material));
  56978. BABYLON.MultiMaterial = MultiMaterial;
  56979. })(BABYLON || (BABYLON = {}));
  56980. //# sourceMappingURL=babylon.multiMaterial.js.map
  56981. var BABYLON;
  56982. (function (BABYLON) {
  56983. var FreeCameraTouchInput = /** @class */ (function () {
  56984. function FreeCameraTouchInput() {
  56985. this._offsetX = null;
  56986. this._offsetY = null;
  56987. this._pointerPressed = new Array();
  56988. this.touchAngularSensibility = 200000.0;
  56989. this.touchMoveSensibility = 250.0;
  56990. }
  56991. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  56992. var _this = this;
  56993. var previousPosition = null;
  56994. if (this._pointerInput === undefined) {
  56995. this._onLostFocus = function (evt) {
  56996. _this._offsetX = null;
  56997. _this._offsetY = null;
  56998. };
  56999. this._pointerInput = function (p, s) {
  57000. var evt = p.event;
  57001. if (evt.pointerType === "mouse") {
  57002. return;
  57003. }
  57004. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  57005. if (!noPreventDefault) {
  57006. evt.preventDefault();
  57007. }
  57008. _this._pointerPressed.push(evt.pointerId);
  57009. if (_this._pointerPressed.length !== 1) {
  57010. return;
  57011. }
  57012. previousPosition = {
  57013. x: evt.clientX,
  57014. y: evt.clientY
  57015. };
  57016. }
  57017. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  57018. if (!noPreventDefault) {
  57019. evt.preventDefault();
  57020. }
  57021. var index = _this._pointerPressed.indexOf(evt.pointerId);
  57022. if (index === -1) {
  57023. return;
  57024. }
  57025. _this._pointerPressed.splice(index, 1);
  57026. if (index != 0) {
  57027. return;
  57028. }
  57029. previousPosition = null;
  57030. _this._offsetX = null;
  57031. _this._offsetY = null;
  57032. }
  57033. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  57034. if (!noPreventDefault) {
  57035. evt.preventDefault();
  57036. }
  57037. if (!previousPosition) {
  57038. return;
  57039. }
  57040. var index = _this._pointerPressed.indexOf(evt.pointerId);
  57041. if (index != 0) {
  57042. return;
  57043. }
  57044. _this._offsetX = evt.clientX - previousPosition.x;
  57045. _this._offsetY = -(evt.clientY - previousPosition.y);
  57046. }
  57047. };
  57048. }
  57049. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  57050. if (this._onLostFocus) {
  57051. element.addEventListener("blur", this._onLostFocus);
  57052. }
  57053. };
  57054. FreeCameraTouchInput.prototype.detachControl = function (element) {
  57055. if (this._pointerInput && element) {
  57056. if (this._observer) {
  57057. this.camera.getScene().onPointerObservable.remove(this._observer);
  57058. this._observer = null;
  57059. }
  57060. if (this._onLostFocus) {
  57061. element.removeEventListener("blur", this._onLostFocus);
  57062. this._onLostFocus = null;
  57063. }
  57064. this._pointerPressed = [];
  57065. this._offsetX = null;
  57066. this._offsetY = null;
  57067. }
  57068. };
  57069. FreeCameraTouchInput.prototype.checkInputs = function () {
  57070. if (this._offsetX && this._offsetY) {
  57071. var camera = this.camera;
  57072. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  57073. if (this._pointerPressed.length > 1) {
  57074. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  57075. }
  57076. else {
  57077. var speed = camera._computeLocalCameraSpeed();
  57078. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  57079. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  57080. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  57081. }
  57082. }
  57083. };
  57084. FreeCameraTouchInput.prototype.getClassName = function () {
  57085. return "FreeCameraTouchInput";
  57086. };
  57087. FreeCameraTouchInput.prototype.getSimpleName = function () {
  57088. return "touch";
  57089. };
  57090. __decorate([
  57091. BABYLON.serialize()
  57092. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  57093. __decorate([
  57094. BABYLON.serialize()
  57095. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  57096. return FreeCameraTouchInput;
  57097. }());
  57098. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  57099. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  57100. })(BABYLON || (BABYLON = {}));
  57101. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  57102. var BABYLON;
  57103. (function (BABYLON) {
  57104. // We're mainly based on the logic defined into the FreeCamera code
  57105. var TouchCamera = /** @class */ (function (_super) {
  57106. __extends(TouchCamera, _super);
  57107. //-- end properties for backward compatibility for inputs
  57108. function TouchCamera(name, position, scene) {
  57109. var _this = _super.call(this, name, position, scene) || this;
  57110. _this.inputs.addTouch();
  57111. _this._setupInputs();
  57112. return _this;
  57113. }
  57114. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  57115. //-- Begin properties for backward compatibility for inputs
  57116. get: function () {
  57117. var touch = this.inputs.attached["touch"];
  57118. if (touch)
  57119. return touch.touchAngularSensibility;
  57120. return 0;
  57121. },
  57122. set: function (value) {
  57123. var touch = this.inputs.attached["touch"];
  57124. if (touch)
  57125. touch.touchAngularSensibility = value;
  57126. },
  57127. enumerable: true,
  57128. configurable: true
  57129. });
  57130. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  57131. get: function () {
  57132. var touch = this.inputs.attached["touch"];
  57133. if (touch)
  57134. return touch.touchMoveSensibility;
  57135. return 0;
  57136. },
  57137. set: function (value) {
  57138. var touch = this.inputs.attached["touch"];
  57139. if (touch)
  57140. touch.touchMoveSensibility = value;
  57141. },
  57142. enumerable: true,
  57143. configurable: true
  57144. });
  57145. TouchCamera.prototype.getClassName = function () {
  57146. return "TouchCamera";
  57147. };
  57148. TouchCamera.prototype._setupInputs = function () {
  57149. var mouse = this.inputs.attached["mouse"];
  57150. if (mouse) {
  57151. mouse.touchEnabled = false;
  57152. }
  57153. };
  57154. return TouchCamera;
  57155. }(BABYLON.FreeCamera));
  57156. BABYLON.TouchCamera = TouchCamera;
  57157. })(BABYLON || (BABYLON = {}));
  57158. //# sourceMappingURL=babylon.touchCamera.js.map
  57159. var BABYLON;
  57160. (function (BABYLON) {
  57161. var ProceduralTexture = /** @class */ (function (_super) {
  57162. __extends(ProceduralTexture, _super);
  57163. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  57164. if (fallbackTexture === void 0) { fallbackTexture = null; }
  57165. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57166. if (isCube === void 0) { isCube = false; }
  57167. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57168. _this.isCube = isCube;
  57169. _this.isEnabled = true;
  57170. _this._currentRefreshId = -1;
  57171. _this._refreshRate = 1;
  57172. _this._vertexBuffers = {};
  57173. _this._uniforms = new Array();
  57174. _this._samplers = new Array();
  57175. _this._textures = {};
  57176. _this._floats = {};
  57177. _this._floatsArrays = {};
  57178. _this._colors3 = {};
  57179. _this._colors4 = {};
  57180. _this._vectors2 = {};
  57181. _this._vectors3 = {};
  57182. _this._matrices = {};
  57183. _this._fallbackTextureUsed = false;
  57184. scene._proceduralTextures.push(_this);
  57185. _this._engine = scene.getEngine();
  57186. _this.name = name;
  57187. _this.isRenderTarget = true;
  57188. _this._size = size;
  57189. _this._generateMipMaps = generateMipMaps;
  57190. _this.setFragment(fragment);
  57191. _this._fallbackTexture = fallbackTexture;
  57192. if (isCube) {
  57193. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  57194. _this.setFloat("face", 0);
  57195. }
  57196. else {
  57197. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  57198. }
  57199. // VBO
  57200. var vertices = [];
  57201. vertices.push(1, 1);
  57202. vertices.push(-1, 1);
  57203. vertices.push(-1, -1);
  57204. vertices.push(1, -1);
  57205. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  57206. _this._createIndexBuffer();
  57207. return _this;
  57208. }
  57209. ProceduralTexture.prototype._createIndexBuffer = function () {
  57210. var engine = this._engine;
  57211. // Indices
  57212. var indices = [];
  57213. indices.push(0);
  57214. indices.push(1);
  57215. indices.push(2);
  57216. indices.push(0);
  57217. indices.push(2);
  57218. indices.push(3);
  57219. this._indexBuffer = engine.createIndexBuffer(indices);
  57220. };
  57221. ProceduralTexture.prototype._rebuild = function () {
  57222. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  57223. if (vb) {
  57224. vb._rebuild();
  57225. }
  57226. this._createIndexBuffer();
  57227. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  57228. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  57229. }
  57230. };
  57231. ProceduralTexture.prototype.reset = function () {
  57232. if (this._effect === undefined) {
  57233. return;
  57234. }
  57235. var engine = this._engine;
  57236. engine._releaseEffect(this._effect);
  57237. };
  57238. ProceduralTexture.prototype.isReady = function () {
  57239. var _this = this;
  57240. var engine = this._engine;
  57241. var shaders;
  57242. if (!this._fragment) {
  57243. return false;
  57244. }
  57245. if (this._fallbackTextureUsed) {
  57246. return true;
  57247. }
  57248. if (this._fragment.fragmentElement !== undefined) {
  57249. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  57250. }
  57251. else {
  57252. shaders = { vertex: "procedural", fragment: this._fragment };
  57253. }
  57254. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  57255. _this.releaseInternalTexture();
  57256. if (_this._fallbackTexture) {
  57257. _this._texture = _this._fallbackTexture._texture;
  57258. if (_this._texture) {
  57259. _this._texture.incrementReferences();
  57260. }
  57261. }
  57262. _this._fallbackTextureUsed = true;
  57263. });
  57264. return this._effect.isReady();
  57265. };
  57266. ProceduralTexture.prototype.resetRefreshCounter = function () {
  57267. this._currentRefreshId = -1;
  57268. };
  57269. ProceduralTexture.prototype.setFragment = function (fragment) {
  57270. this._fragment = fragment;
  57271. };
  57272. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  57273. get: function () {
  57274. return this._refreshRate;
  57275. },
  57276. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57277. set: function (value) {
  57278. this._refreshRate = value;
  57279. this.resetRefreshCounter();
  57280. },
  57281. enumerable: true,
  57282. configurable: true
  57283. });
  57284. ProceduralTexture.prototype._shouldRender = function () {
  57285. if (!this.isEnabled || !this.isReady() || !this._texture) {
  57286. return false;
  57287. }
  57288. if (this._fallbackTextureUsed) {
  57289. return false;
  57290. }
  57291. if (this._currentRefreshId === -1) {
  57292. this._currentRefreshId = 1;
  57293. return true;
  57294. }
  57295. if (this.refreshRate === this._currentRefreshId) {
  57296. this._currentRefreshId = 1;
  57297. return true;
  57298. }
  57299. this._currentRefreshId++;
  57300. return false;
  57301. };
  57302. ProceduralTexture.prototype.getRenderSize = function () {
  57303. return this._size;
  57304. };
  57305. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  57306. if (this._fallbackTextureUsed) {
  57307. return;
  57308. }
  57309. this.releaseInternalTexture();
  57310. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  57311. };
  57312. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  57313. if (this._uniforms.indexOf(uniformName) === -1) {
  57314. this._uniforms.push(uniformName);
  57315. }
  57316. };
  57317. ProceduralTexture.prototype.setTexture = function (name, texture) {
  57318. if (this._samplers.indexOf(name) === -1) {
  57319. this._samplers.push(name);
  57320. }
  57321. this._textures[name] = texture;
  57322. return this;
  57323. };
  57324. ProceduralTexture.prototype.setFloat = function (name, value) {
  57325. this._checkUniform(name);
  57326. this._floats[name] = value;
  57327. return this;
  57328. };
  57329. ProceduralTexture.prototype.setFloats = function (name, value) {
  57330. this._checkUniform(name);
  57331. this._floatsArrays[name] = value;
  57332. return this;
  57333. };
  57334. ProceduralTexture.prototype.setColor3 = function (name, value) {
  57335. this._checkUniform(name);
  57336. this._colors3[name] = value;
  57337. return this;
  57338. };
  57339. ProceduralTexture.prototype.setColor4 = function (name, value) {
  57340. this._checkUniform(name);
  57341. this._colors4[name] = value;
  57342. return this;
  57343. };
  57344. ProceduralTexture.prototype.setVector2 = function (name, value) {
  57345. this._checkUniform(name);
  57346. this._vectors2[name] = value;
  57347. return this;
  57348. };
  57349. ProceduralTexture.prototype.setVector3 = function (name, value) {
  57350. this._checkUniform(name);
  57351. this._vectors3[name] = value;
  57352. return this;
  57353. };
  57354. ProceduralTexture.prototype.setMatrix = function (name, value) {
  57355. this._checkUniform(name);
  57356. this._matrices[name] = value;
  57357. return this;
  57358. };
  57359. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  57360. var scene = this.getScene();
  57361. if (!scene) {
  57362. return;
  57363. }
  57364. var engine = this._engine;
  57365. // Render
  57366. engine.enableEffect(this._effect);
  57367. engine.setState(false);
  57368. // Texture
  57369. for (var name in this._textures) {
  57370. this._effect.setTexture(name, this._textures[name]);
  57371. }
  57372. // Float
  57373. for (name in this._floats) {
  57374. this._effect.setFloat(name, this._floats[name]);
  57375. }
  57376. // Floats
  57377. for (name in this._floatsArrays) {
  57378. this._effect.setArray(name, this._floatsArrays[name]);
  57379. }
  57380. // Color3
  57381. for (name in this._colors3) {
  57382. this._effect.setColor3(name, this._colors3[name]);
  57383. }
  57384. // Color4
  57385. for (name in this._colors4) {
  57386. var color = this._colors4[name];
  57387. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  57388. }
  57389. // Vector2
  57390. for (name in this._vectors2) {
  57391. this._effect.setVector2(name, this._vectors2[name]);
  57392. }
  57393. // Vector3
  57394. for (name in this._vectors3) {
  57395. this._effect.setVector3(name, this._vectors3[name]);
  57396. }
  57397. // Matrix
  57398. for (name in this._matrices) {
  57399. this._effect.setMatrix(name, this._matrices[name]);
  57400. }
  57401. if (!this._texture) {
  57402. return;
  57403. }
  57404. if (this.isCube) {
  57405. for (var face = 0; face < 6; face++) {
  57406. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  57407. // VBOs
  57408. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  57409. this._effect.setFloat("face", face);
  57410. // Clear
  57411. engine.clear(scene.clearColor, true, true, true);
  57412. // Draw order
  57413. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  57414. // Mipmaps
  57415. if (face === 5) {
  57416. engine.generateMipMapsForCubemap(this._texture);
  57417. }
  57418. }
  57419. }
  57420. else {
  57421. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  57422. // VBOs
  57423. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  57424. // Clear
  57425. engine.clear(scene.clearColor, true, true, true);
  57426. // Draw order
  57427. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  57428. }
  57429. // Unbind
  57430. engine.unBindFramebuffer(this._texture, this.isCube);
  57431. if (this.onGenerated) {
  57432. this.onGenerated();
  57433. }
  57434. };
  57435. ProceduralTexture.prototype.clone = function () {
  57436. var textureSize = this.getSize();
  57437. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  57438. // Base texture
  57439. newTexture.hasAlpha = this.hasAlpha;
  57440. newTexture.level = this.level;
  57441. // RenderTarget Texture
  57442. newTexture.coordinatesMode = this.coordinatesMode;
  57443. return newTexture;
  57444. };
  57445. ProceduralTexture.prototype.dispose = function () {
  57446. var scene = this.getScene();
  57447. if (!scene) {
  57448. return;
  57449. }
  57450. var index = scene._proceduralTextures.indexOf(this);
  57451. if (index >= 0) {
  57452. scene._proceduralTextures.splice(index, 1);
  57453. }
  57454. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  57455. if (vertexBuffer) {
  57456. vertexBuffer.dispose();
  57457. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  57458. }
  57459. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  57460. this._indexBuffer = null;
  57461. }
  57462. _super.prototype.dispose.call(this);
  57463. };
  57464. return ProceduralTexture;
  57465. }(BABYLON.Texture));
  57466. BABYLON.ProceduralTexture = ProceduralTexture;
  57467. })(BABYLON || (BABYLON = {}));
  57468. //# sourceMappingURL=babylon.proceduralTexture.js.map
  57469. var BABYLON;
  57470. (function (BABYLON) {
  57471. var CustomProceduralTexture = /** @class */ (function (_super) {
  57472. __extends(CustomProceduralTexture, _super);
  57473. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  57474. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  57475. _this._animate = true;
  57476. _this._time = 0;
  57477. _this._texturePath = texturePath;
  57478. //Try to load json
  57479. _this.loadJson(texturePath);
  57480. _this.refreshRate = 1;
  57481. return _this;
  57482. }
  57483. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  57484. var _this = this;
  57485. var noConfigFile = function () {
  57486. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  57487. try {
  57488. _this.setFragment(_this._texturePath);
  57489. }
  57490. catch (ex) {
  57491. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  57492. }
  57493. };
  57494. var configFileUrl = jsonUrl + "/config.json";
  57495. var xhr = new XMLHttpRequest();
  57496. xhr.open("GET", configFileUrl, true);
  57497. xhr.addEventListener("load", function () {
  57498. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  57499. try {
  57500. _this._config = JSON.parse(xhr.response);
  57501. _this.updateShaderUniforms();
  57502. _this.updateTextures();
  57503. _this.setFragment(_this._texturePath + "/custom");
  57504. _this._animate = _this._config.animate;
  57505. _this.refreshRate = _this._config.refreshrate;
  57506. }
  57507. catch (ex) {
  57508. noConfigFile();
  57509. }
  57510. }
  57511. else {
  57512. noConfigFile();
  57513. }
  57514. }, false);
  57515. xhr.addEventListener("error", function () {
  57516. noConfigFile();
  57517. }, false);
  57518. try {
  57519. xhr.send();
  57520. }
  57521. catch (ex) {
  57522. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  57523. }
  57524. };
  57525. CustomProceduralTexture.prototype.isReady = function () {
  57526. if (!_super.prototype.isReady.call(this)) {
  57527. return false;
  57528. }
  57529. for (var name in this._textures) {
  57530. var texture = this._textures[name];
  57531. if (!texture.isReady()) {
  57532. return false;
  57533. }
  57534. }
  57535. return true;
  57536. };
  57537. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  57538. var scene = this.getScene();
  57539. if (this._animate && scene) {
  57540. this._time += scene.getAnimationRatio() * 0.03;
  57541. this.updateShaderUniforms();
  57542. }
  57543. _super.prototype.render.call(this, useCameraPostProcess);
  57544. };
  57545. CustomProceduralTexture.prototype.updateTextures = function () {
  57546. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  57547. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  57548. }
  57549. };
  57550. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  57551. if (this._config) {
  57552. for (var j = 0; j < this._config.uniforms.length; j++) {
  57553. var uniform = this._config.uniforms[j];
  57554. switch (uniform.type) {
  57555. case "float":
  57556. this.setFloat(uniform.name, uniform.value);
  57557. break;
  57558. case "color3":
  57559. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  57560. break;
  57561. case "color4":
  57562. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  57563. break;
  57564. case "vector2":
  57565. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  57566. break;
  57567. case "vector3":
  57568. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  57569. break;
  57570. }
  57571. }
  57572. }
  57573. this.setFloat("time", this._time);
  57574. };
  57575. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  57576. get: function () {
  57577. return this._animate;
  57578. },
  57579. set: function (value) {
  57580. this._animate = value;
  57581. },
  57582. enumerable: true,
  57583. configurable: true
  57584. });
  57585. return CustomProceduralTexture;
  57586. }(BABYLON.ProceduralTexture));
  57587. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  57588. })(BABYLON || (BABYLON = {}));
  57589. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  57590. var BABYLON;
  57591. (function (BABYLON) {
  57592. var FreeCameraGamepadInput = /** @class */ (function () {
  57593. function FreeCameraGamepadInput() {
  57594. this.gamepadAngularSensibility = 200;
  57595. this.gamepadMoveSensibility = 40;
  57596. // private members
  57597. this._cameraTransform = BABYLON.Matrix.Identity();
  57598. this._deltaTransform = BABYLON.Vector3.Zero();
  57599. this._vector3 = BABYLON.Vector3.Zero();
  57600. this._vector2 = BABYLON.Vector2.Zero();
  57601. }
  57602. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  57603. var _this = this;
  57604. var manager = this.camera.getScene().gamepadManager;
  57605. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  57606. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  57607. // prioritize XBOX gamepads.
  57608. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  57609. _this.gamepad = gamepad;
  57610. }
  57611. }
  57612. });
  57613. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  57614. if (_this.gamepad === gamepad) {
  57615. _this.gamepad = null;
  57616. }
  57617. });
  57618. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  57619. };
  57620. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  57621. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  57622. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  57623. this.gamepad = null;
  57624. };
  57625. FreeCameraGamepadInput.prototype.checkInputs = function () {
  57626. if (this.gamepad && this.gamepad.leftStick) {
  57627. var camera = this.camera;
  57628. var LSValues = this.gamepad.leftStick;
  57629. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  57630. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  57631. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  57632. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  57633. var RSValues = this.gamepad.rightStick;
  57634. if (RSValues) {
  57635. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  57636. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  57637. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  57638. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  57639. }
  57640. else {
  57641. RSValues = { x: 0, y: 0 };
  57642. }
  57643. if (!camera.rotationQuaternion) {
  57644. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  57645. }
  57646. else {
  57647. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  57648. }
  57649. var speed = camera._computeLocalCameraSpeed() * 50.0;
  57650. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  57651. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  57652. camera.cameraDirection.addInPlace(this._deltaTransform);
  57653. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  57654. camera.cameraRotation.addInPlace(this._vector2);
  57655. }
  57656. };
  57657. FreeCameraGamepadInput.prototype.getClassName = function () {
  57658. return "FreeCameraGamepadInput";
  57659. };
  57660. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  57661. return "gamepad";
  57662. };
  57663. __decorate([
  57664. BABYLON.serialize()
  57665. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  57666. __decorate([
  57667. BABYLON.serialize()
  57668. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  57669. return FreeCameraGamepadInput;
  57670. }());
  57671. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  57672. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  57673. })(BABYLON || (BABYLON = {}));
  57674. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  57675. var BABYLON;
  57676. (function (BABYLON) {
  57677. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  57678. function ArcRotateCameraGamepadInput() {
  57679. this.gamepadRotationSensibility = 80;
  57680. this.gamepadMoveSensibility = 40;
  57681. }
  57682. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  57683. var _this = this;
  57684. var manager = this.camera.getScene().gamepadManager;
  57685. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  57686. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  57687. // prioritize XBOX gamepads.
  57688. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  57689. _this.gamepad = gamepad;
  57690. }
  57691. }
  57692. });
  57693. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  57694. if (_this.gamepad === gamepad) {
  57695. _this.gamepad = null;
  57696. }
  57697. });
  57698. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  57699. };
  57700. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  57701. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  57702. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  57703. this.gamepad = null;
  57704. };
  57705. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  57706. if (this.gamepad) {
  57707. var camera = this.camera;
  57708. var RSValues = this.gamepad.rightStick;
  57709. if (RSValues) {
  57710. if (RSValues.x != 0) {
  57711. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  57712. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  57713. camera.inertialAlphaOffset += normalizedRX;
  57714. }
  57715. }
  57716. if (RSValues.y != 0) {
  57717. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  57718. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  57719. camera.inertialBetaOffset += normalizedRY;
  57720. }
  57721. }
  57722. }
  57723. var LSValues = this.gamepad.leftStick;
  57724. if (LSValues && LSValues.y != 0) {
  57725. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  57726. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  57727. this.camera.inertialRadiusOffset -= normalizedLY;
  57728. }
  57729. }
  57730. }
  57731. };
  57732. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  57733. return "ArcRotateCameraGamepadInput";
  57734. };
  57735. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  57736. return "gamepad";
  57737. };
  57738. __decorate([
  57739. BABYLON.serialize()
  57740. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  57741. __decorate([
  57742. BABYLON.serialize()
  57743. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  57744. return ArcRotateCameraGamepadInput;
  57745. }());
  57746. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  57747. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  57748. })(BABYLON || (BABYLON = {}));
  57749. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  57750. var BABYLON;
  57751. (function (BABYLON) {
  57752. var GamepadManager = /** @class */ (function () {
  57753. function GamepadManager(_scene) {
  57754. var _this = this;
  57755. this._scene = _scene;
  57756. this._babylonGamepads = [];
  57757. this._oneGamepadConnected = false;
  57758. this._isMonitoring = false;
  57759. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  57760. if (!BABYLON.Tools.IsWindowObjectExist()) {
  57761. this._gamepadEventSupported = false;
  57762. }
  57763. else {
  57764. this._gamepadEventSupported = 'GamepadEvent' in window;
  57765. this._gamepadSupport = (navigator.getGamepads ||
  57766. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  57767. }
  57768. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  57769. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  57770. for (var i in _this._babylonGamepads) {
  57771. var gamepad = _this._babylonGamepads[i];
  57772. if (gamepad && gamepad._isConnected) {
  57773. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  57774. }
  57775. }
  57776. });
  57777. this._onGamepadConnectedEvent = function (evt) {
  57778. var gamepad = evt.gamepad;
  57779. if (gamepad.index in _this._babylonGamepads) {
  57780. if (_this._babylonGamepads[gamepad.index].isConnected) {
  57781. return;
  57782. }
  57783. }
  57784. var newGamepad;
  57785. if (_this._babylonGamepads[gamepad.index]) {
  57786. newGamepad = _this._babylonGamepads[gamepad.index];
  57787. newGamepad.browserGamepad = gamepad;
  57788. newGamepad._isConnected = true;
  57789. }
  57790. else {
  57791. newGamepad = _this._addNewGamepad(gamepad);
  57792. }
  57793. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57794. _this._startMonitoringGamepads();
  57795. };
  57796. this._onGamepadDisconnectedEvent = function (evt) {
  57797. var gamepad = evt.gamepad;
  57798. // Remove the gamepad from the list of gamepads to monitor.
  57799. for (var i in _this._babylonGamepads) {
  57800. if (_this._babylonGamepads[i].index === gamepad.index) {
  57801. var disconnectedGamepad = _this._babylonGamepads[i];
  57802. disconnectedGamepad._isConnected = false;
  57803. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  57804. break;
  57805. }
  57806. }
  57807. };
  57808. if (this._gamepadSupport) {
  57809. //first add already-connected gamepads
  57810. this._updateGamepadObjects();
  57811. if (this._babylonGamepads.length) {
  57812. this._startMonitoringGamepads();
  57813. }
  57814. // Checking if the gamepad connected event is supported (like in Firefox)
  57815. if (this._gamepadEventSupported) {
  57816. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  57817. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  57818. }
  57819. else {
  57820. this._startMonitoringGamepads();
  57821. }
  57822. }
  57823. }
  57824. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  57825. get: function () {
  57826. return this._babylonGamepads;
  57827. },
  57828. enumerable: true,
  57829. configurable: true
  57830. });
  57831. GamepadManager.prototype.getGamepadByType = function (type) {
  57832. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  57833. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  57834. var gamepad = _a[_i];
  57835. if (gamepad && gamepad.type === type) {
  57836. return gamepad;
  57837. }
  57838. }
  57839. return null;
  57840. };
  57841. GamepadManager.prototype.dispose = function () {
  57842. if (this._gamepadEventSupported) {
  57843. if (this._onGamepadConnectedEvent) {
  57844. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  57845. }
  57846. if (this._onGamepadDisconnectedEvent) {
  57847. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  57848. }
  57849. this._onGamepadConnectedEvent = null;
  57850. this._onGamepadDisconnectedEvent = null;
  57851. }
  57852. this._babylonGamepads.forEach(function (gamepad) {
  57853. gamepad.dispose();
  57854. });
  57855. this.onGamepadConnectedObservable.clear();
  57856. this.onGamepadDisconnectedObservable.clear();
  57857. this._oneGamepadConnected = false;
  57858. this._stopMonitoringGamepads();
  57859. this._babylonGamepads = [];
  57860. };
  57861. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  57862. if (!this._oneGamepadConnected) {
  57863. this._oneGamepadConnected = true;
  57864. }
  57865. var newGamepad;
  57866. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  57867. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  57868. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  57869. }
  57870. else if (gamepad.pose) {
  57871. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  57872. }
  57873. else {
  57874. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  57875. }
  57876. this._babylonGamepads[newGamepad.index] = newGamepad;
  57877. return newGamepad;
  57878. };
  57879. GamepadManager.prototype._startMonitoringGamepads = function () {
  57880. if (!this._isMonitoring) {
  57881. this._isMonitoring = true;
  57882. //back-comp
  57883. if (!this._scene) {
  57884. this._checkGamepadsStatus();
  57885. }
  57886. }
  57887. };
  57888. GamepadManager.prototype._stopMonitoringGamepads = function () {
  57889. this._isMonitoring = false;
  57890. };
  57891. GamepadManager.prototype._checkGamepadsStatus = function () {
  57892. var _this = this;
  57893. // Hack to be compatible Chrome
  57894. this._updateGamepadObjects();
  57895. for (var i in this._babylonGamepads) {
  57896. var gamepad = this._babylonGamepads[i];
  57897. if (!gamepad || !gamepad.isConnected) {
  57898. continue;
  57899. }
  57900. gamepad.update();
  57901. }
  57902. if (this._isMonitoring && !this._scene) {
  57903. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  57904. }
  57905. };
  57906. // This function is called only on Chrome, which does not properly support
  57907. // connection/disconnection events and forces you to recopy again the gamepad object
  57908. GamepadManager.prototype._updateGamepadObjects = function () {
  57909. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  57910. for (var i = 0; i < gamepads.length; i++) {
  57911. if (gamepads[i]) {
  57912. if (!this._babylonGamepads[gamepads[i].index]) {
  57913. var newGamepad = this._addNewGamepad(gamepads[i]);
  57914. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57915. }
  57916. else {
  57917. // Forced to copy again this object for Chrome for unknown reason
  57918. this._babylonGamepads[i].browserGamepad = gamepads[i];
  57919. if (!this._babylonGamepads[i].isConnected) {
  57920. this._babylonGamepads[i]._isConnected = true;
  57921. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  57922. }
  57923. }
  57924. }
  57925. }
  57926. };
  57927. return GamepadManager;
  57928. }());
  57929. BABYLON.GamepadManager = GamepadManager;
  57930. })(BABYLON || (BABYLON = {}));
  57931. //# sourceMappingURL=babylon.gamepadManager.js.map
  57932. var BABYLON;
  57933. (function (BABYLON) {
  57934. var StickValues = /** @class */ (function () {
  57935. function StickValues(x, y) {
  57936. this.x = x;
  57937. this.y = y;
  57938. }
  57939. return StickValues;
  57940. }());
  57941. BABYLON.StickValues = StickValues;
  57942. var Gamepad = /** @class */ (function () {
  57943. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  57944. if (leftStickX === void 0) { leftStickX = 0; }
  57945. if (leftStickY === void 0) { leftStickY = 1; }
  57946. if (rightStickX === void 0) { rightStickX = 2; }
  57947. if (rightStickY === void 0) { rightStickY = 3; }
  57948. this.id = id;
  57949. this.index = index;
  57950. this.browserGamepad = browserGamepad;
  57951. this._isConnected = true;
  57952. this._invertLeftStickY = false;
  57953. this.type = Gamepad.GAMEPAD;
  57954. this._leftStickAxisX = leftStickX;
  57955. this._leftStickAxisY = leftStickY;
  57956. this._rightStickAxisX = rightStickX;
  57957. this._rightStickAxisY = rightStickY;
  57958. if (this.browserGamepad.axes.length >= 2) {
  57959. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57960. }
  57961. if (this.browserGamepad.axes.length >= 4) {
  57962. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57963. }
  57964. }
  57965. Object.defineProperty(Gamepad.prototype, "isConnected", {
  57966. get: function () {
  57967. return this._isConnected;
  57968. },
  57969. enumerable: true,
  57970. configurable: true
  57971. });
  57972. Gamepad.prototype.onleftstickchanged = function (callback) {
  57973. this._onleftstickchanged = callback;
  57974. };
  57975. Gamepad.prototype.onrightstickchanged = function (callback) {
  57976. this._onrightstickchanged = callback;
  57977. };
  57978. Object.defineProperty(Gamepad.prototype, "leftStick", {
  57979. get: function () {
  57980. return this._leftStick;
  57981. },
  57982. set: function (newValues) {
  57983. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  57984. this._onleftstickchanged(newValues);
  57985. }
  57986. this._leftStick = newValues;
  57987. },
  57988. enumerable: true,
  57989. configurable: true
  57990. });
  57991. Object.defineProperty(Gamepad.prototype, "rightStick", {
  57992. get: function () {
  57993. return this._rightStick;
  57994. },
  57995. set: function (newValues) {
  57996. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  57997. this._onrightstickchanged(newValues);
  57998. }
  57999. this._rightStick = newValues;
  58000. },
  58001. enumerable: true,
  58002. configurable: true
  58003. });
  58004. Gamepad.prototype.update = function () {
  58005. if (this._leftStick) {
  58006. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  58007. if (this._invertLeftStickY) {
  58008. this.leftStick.y *= -1;
  58009. }
  58010. }
  58011. if (this._rightStick) {
  58012. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  58013. }
  58014. };
  58015. Gamepad.prototype.dispose = function () {
  58016. };
  58017. Gamepad.GAMEPAD = 0;
  58018. Gamepad.GENERIC = 1;
  58019. Gamepad.XBOX = 2;
  58020. Gamepad.POSE_ENABLED = 3;
  58021. return Gamepad;
  58022. }());
  58023. BABYLON.Gamepad = Gamepad;
  58024. var GenericPad = /** @class */ (function (_super) {
  58025. __extends(GenericPad, _super);
  58026. function GenericPad(id, index, browserGamepad) {
  58027. var _this = _super.call(this, id, index, browserGamepad) || this;
  58028. _this.onButtonDownObservable = new BABYLON.Observable();
  58029. _this.onButtonUpObservable = new BABYLON.Observable();
  58030. _this.type = Gamepad.GENERIC;
  58031. _this._buttons = new Array(browserGamepad.buttons.length);
  58032. return _this;
  58033. }
  58034. GenericPad.prototype.onbuttondown = function (callback) {
  58035. this._onbuttondown = callback;
  58036. };
  58037. GenericPad.prototype.onbuttonup = function (callback) {
  58038. this._onbuttonup = callback;
  58039. };
  58040. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  58041. if (newValue !== currentValue) {
  58042. if (newValue === 1) {
  58043. if (this._onbuttondown) {
  58044. this._onbuttondown(buttonIndex);
  58045. }
  58046. this.onButtonDownObservable.notifyObservers(buttonIndex);
  58047. }
  58048. if (newValue === 0) {
  58049. if (this._onbuttonup) {
  58050. this._onbuttonup(buttonIndex);
  58051. }
  58052. this.onButtonUpObservable.notifyObservers(buttonIndex);
  58053. }
  58054. }
  58055. return newValue;
  58056. };
  58057. GenericPad.prototype.update = function () {
  58058. _super.prototype.update.call(this);
  58059. for (var index = 0; index < this._buttons.length; index++) {
  58060. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  58061. }
  58062. };
  58063. GenericPad.prototype.dispose = function () {
  58064. _super.prototype.dispose.call(this);
  58065. this.onButtonDownObservable.clear();
  58066. this.onButtonUpObservable.clear();
  58067. };
  58068. return GenericPad;
  58069. }(Gamepad));
  58070. BABYLON.GenericPad = GenericPad;
  58071. })(BABYLON || (BABYLON = {}));
  58072. //# sourceMappingURL=babylon.gamepad.js.map
  58073. var BABYLON;
  58074. (function (BABYLON) {
  58075. var Xbox360Button;
  58076. (function (Xbox360Button) {
  58077. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  58078. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  58079. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  58080. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  58081. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  58082. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  58083. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  58084. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  58085. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  58086. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  58087. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  58088. var Xbox360Dpad;
  58089. (function (Xbox360Dpad) {
  58090. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  58091. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  58092. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  58093. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  58094. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  58095. var Xbox360Pad = /** @class */ (function (_super) {
  58096. __extends(Xbox360Pad, _super);
  58097. function Xbox360Pad(id, index, gamepad, xboxOne) {
  58098. if (xboxOne === void 0) { xboxOne = false; }
  58099. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  58100. _this._leftTrigger = 0;
  58101. _this._rightTrigger = 0;
  58102. _this.onButtonDownObservable = new BABYLON.Observable();
  58103. _this.onButtonUpObservable = new BABYLON.Observable();
  58104. _this.onPadDownObservable = new BABYLON.Observable();
  58105. _this.onPadUpObservable = new BABYLON.Observable();
  58106. _this._buttonA = 0;
  58107. _this._buttonB = 0;
  58108. _this._buttonX = 0;
  58109. _this._buttonY = 0;
  58110. _this._buttonBack = 0;
  58111. _this._buttonStart = 0;
  58112. _this._buttonLB = 0;
  58113. _this._buttonRB = 0;
  58114. _this._buttonLeftStick = 0;
  58115. _this._buttonRightStick = 0;
  58116. _this._dPadUp = 0;
  58117. _this._dPadDown = 0;
  58118. _this._dPadLeft = 0;
  58119. _this._dPadRight = 0;
  58120. _this._isXboxOnePad = false;
  58121. _this.type = BABYLON.Gamepad.XBOX;
  58122. _this._isXboxOnePad = xboxOne;
  58123. return _this;
  58124. }
  58125. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  58126. this._onlefttriggerchanged = callback;
  58127. };
  58128. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  58129. this._onrighttriggerchanged = callback;
  58130. };
  58131. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  58132. get: function () {
  58133. return this._leftTrigger;
  58134. },
  58135. set: function (newValue) {
  58136. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  58137. this._onlefttriggerchanged(newValue);
  58138. }
  58139. this._leftTrigger = newValue;
  58140. },
  58141. enumerable: true,
  58142. configurable: true
  58143. });
  58144. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  58145. get: function () {
  58146. return this._rightTrigger;
  58147. },
  58148. set: function (newValue) {
  58149. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  58150. this._onrighttriggerchanged(newValue);
  58151. }
  58152. this._rightTrigger = newValue;
  58153. },
  58154. enumerable: true,
  58155. configurable: true
  58156. });
  58157. Xbox360Pad.prototype.onbuttondown = function (callback) {
  58158. this._onbuttondown = callback;
  58159. };
  58160. Xbox360Pad.prototype.onbuttonup = function (callback) {
  58161. this._onbuttonup = callback;
  58162. };
  58163. Xbox360Pad.prototype.ondpaddown = function (callback) {
  58164. this._ondpaddown = callback;
  58165. };
  58166. Xbox360Pad.prototype.ondpadup = function (callback) {
  58167. this._ondpadup = callback;
  58168. };
  58169. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  58170. if (newValue !== currentValue) {
  58171. if (newValue === 1) {
  58172. if (this._onbuttondown) {
  58173. this._onbuttondown(buttonType);
  58174. }
  58175. this.onButtonDownObservable.notifyObservers(buttonType);
  58176. }
  58177. if (newValue === 0) {
  58178. if (this._onbuttonup) {
  58179. this._onbuttonup(buttonType);
  58180. }
  58181. this.onButtonUpObservable.notifyObservers(buttonType);
  58182. }
  58183. }
  58184. return newValue;
  58185. };
  58186. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  58187. if (newValue !== currentValue) {
  58188. if (newValue === 1) {
  58189. if (this._ondpaddown) {
  58190. this._ondpaddown(buttonType);
  58191. }
  58192. this.onPadDownObservable.notifyObservers(buttonType);
  58193. }
  58194. if (newValue === 0) {
  58195. if (this._ondpadup) {
  58196. this._ondpadup(buttonType);
  58197. }
  58198. this.onPadUpObservable.notifyObservers(buttonType);
  58199. }
  58200. }
  58201. return newValue;
  58202. };
  58203. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  58204. get: function () {
  58205. return this._buttonA;
  58206. },
  58207. set: function (value) {
  58208. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  58209. },
  58210. enumerable: true,
  58211. configurable: true
  58212. });
  58213. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  58214. get: function () {
  58215. return this._buttonB;
  58216. },
  58217. set: function (value) {
  58218. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  58219. },
  58220. enumerable: true,
  58221. configurable: true
  58222. });
  58223. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  58224. get: function () {
  58225. return this._buttonX;
  58226. },
  58227. set: function (value) {
  58228. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  58229. },
  58230. enumerable: true,
  58231. configurable: true
  58232. });
  58233. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  58234. get: function () {
  58235. return this._buttonY;
  58236. },
  58237. set: function (value) {
  58238. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  58239. },
  58240. enumerable: true,
  58241. configurable: true
  58242. });
  58243. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  58244. get: function () {
  58245. return this._buttonStart;
  58246. },
  58247. set: function (value) {
  58248. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  58249. },
  58250. enumerable: true,
  58251. configurable: true
  58252. });
  58253. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  58254. get: function () {
  58255. return this._buttonBack;
  58256. },
  58257. set: function (value) {
  58258. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  58259. },
  58260. enumerable: true,
  58261. configurable: true
  58262. });
  58263. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  58264. get: function () {
  58265. return this._buttonLB;
  58266. },
  58267. set: function (value) {
  58268. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  58269. },
  58270. enumerable: true,
  58271. configurable: true
  58272. });
  58273. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  58274. get: function () {
  58275. return this._buttonRB;
  58276. },
  58277. set: function (value) {
  58278. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  58279. },
  58280. enumerable: true,
  58281. configurable: true
  58282. });
  58283. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  58284. get: function () {
  58285. return this._buttonLeftStick;
  58286. },
  58287. set: function (value) {
  58288. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  58289. },
  58290. enumerable: true,
  58291. configurable: true
  58292. });
  58293. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  58294. get: function () {
  58295. return this._buttonRightStick;
  58296. },
  58297. set: function (value) {
  58298. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  58299. },
  58300. enumerable: true,
  58301. configurable: true
  58302. });
  58303. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  58304. get: function () {
  58305. return this._dPadUp;
  58306. },
  58307. set: function (value) {
  58308. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  58309. },
  58310. enumerable: true,
  58311. configurable: true
  58312. });
  58313. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  58314. get: function () {
  58315. return this._dPadDown;
  58316. },
  58317. set: function (value) {
  58318. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  58319. },
  58320. enumerable: true,
  58321. configurable: true
  58322. });
  58323. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  58324. get: function () {
  58325. return this._dPadLeft;
  58326. },
  58327. set: function (value) {
  58328. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  58329. },
  58330. enumerable: true,
  58331. configurable: true
  58332. });
  58333. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  58334. get: function () {
  58335. return this._dPadRight;
  58336. },
  58337. set: function (value) {
  58338. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  58339. },
  58340. enumerable: true,
  58341. configurable: true
  58342. });
  58343. Xbox360Pad.prototype.update = function () {
  58344. _super.prototype.update.call(this);
  58345. if (this._isXboxOnePad) {
  58346. this.buttonA = this.browserGamepad.buttons[0].value;
  58347. this.buttonB = this.browserGamepad.buttons[1].value;
  58348. this.buttonX = this.browserGamepad.buttons[2].value;
  58349. this.buttonY = this.browserGamepad.buttons[3].value;
  58350. this.buttonLB = this.browserGamepad.buttons[4].value;
  58351. this.buttonRB = this.browserGamepad.buttons[5].value;
  58352. this.leftTrigger = this.browserGamepad.axes[2];
  58353. this.rightTrigger = this.browserGamepad.axes[5];
  58354. this.buttonBack = this.browserGamepad.buttons[9].value;
  58355. this.buttonStart = this.browserGamepad.buttons[8].value;
  58356. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  58357. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  58358. this.dPadUp = this.browserGamepad.buttons[11].value;
  58359. this.dPadDown = this.browserGamepad.buttons[12].value;
  58360. this.dPadLeft = this.browserGamepad.buttons[13].value;
  58361. this.dPadRight = this.browserGamepad.buttons[14].value;
  58362. }
  58363. else {
  58364. this.buttonA = this.browserGamepad.buttons[0].value;
  58365. this.buttonB = this.browserGamepad.buttons[1].value;
  58366. this.buttonX = this.browserGamepad.buttons[2].value;
  58367. this.buttonY = this.browserGamepad.buttons[3].value;
  58368. this.buttonLB = this.browserGamepad.buttons[4].value;
  58369. this.buttonRB = this.browserGamepad.buttons[5].value;
  58370. this.leftTrigger = this.browserGamepad.buttons[6].value;
  58371. this.rightTrigger = this.browserGamepad.buttons[7].value;
  58372. this.buttonBack = this.browserGamepad.buttons[8].value;
  58373. this.buttonStart = this.browserGamepad.buttons[9].value;
  58374. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  58375. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  58376. this.dPadUp = this.browserGamepad.buttons[12].value;
  58377. this.dPadDown = this.browserGamepad.buttons[13].value;
  58378. this.dPadLeft = this.browserGamepad.buttons[14].value;
  58379. this.dPadRight = this.browserGamepad.buttons[15].value;
  58380. }
  58381. };
  58382. Xbox360Pad.prototype.dispose = function () {
  58383. _super.prototype.dispose.call(this);
  58384. this.onButtonDownObservable.clear();
  58385. this.onButtonUpObservable.clear();
  58386. this.onPadDownObservable.clear();
  58387. this.onPadUpObservable.clear();
  58388. };
  58389. return Xbox360Pad;
  58390. }(BABYLON.Gamepad));
  58391. BABYLON.Xbox360Pad = Xbox360Pad;
  58392. })(BABYLON || (BABYLON = {}));
  58393. //# sourceMappingURL=babylon.xboxGamepad.js.map
  58394. var BABYLON;
  58395. (function (BABYLON) {
  58396. var PoseEnabledControllerType;
  58397. (function (PoseEnabledControllerType) {
  58398. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  58399. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  58400. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  58401. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  58402. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  58403. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  58404. var PoseEnabledControllerHelper = /** @class */ (function () {
  58405. function PoseEnabledControllerHelper() {
  58406. }
  58407. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  58408. // Oculus Touch
  58409. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  58410. return new BABYLON.OculusTouchController(vrGamepad);
  58411. }
  58412. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  58413. return new BABYLON.WindowsMotionController(vrGamepad);
  58414. }
  58415. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  58416. return new BABYLON.ViveController(vrGamepad);
  58417. }
  58418. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  58419. return new BABYLON.GearVRController(vrGamepad);
  58420. }
  58421. else {
  58422. return new BABYLON.GenericController(vrGamepad);
  58423. }
  58424. };
  58425. return PoseEnabledControllerHelper;
  58426. }());
  58427. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  58428. var PoseEnabledController = /** @class */ (function (_super) {
  58429. __extends(PoseEnabledController, _super);
  58430. function PoseEnabledController(browserGamepad) {
  58431. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  58432. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  58433. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  58434. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  58435. // Represents device position and rotation in babylon space
  58436. _this.devicePosition = BABYLON.Vector3.Zero();
  58437. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  58438. _this.deviceScaleFactor = 1;
  58439. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  58440. _this._deviceToWorld = BABYLON.Matrix.Identity();
  58441. _this._workingMatrix = BABYLON.Matrix.Identity();
  58442. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  58443. _this.controllerType = PoseEnabledControllerType.GENERIC;
  58444. _this.position = BABYLON.Vector3.Zero();
  58445. _this.rotationQuaternion = new BABYLON.Quaternion();
  58446. _this._calculatedPosition = BABYLON.Vector3.Zero();
  58447. _this._calculatedRotation = new BABYLON.Quaternion();
  58448. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  58449. return _this;
  58450. }
  58451. PoseEnabledController.prototype.update = function () {
  58452. _super.prototype.update.call(this);
  58453. var pose = this.browserGamepad.pose;
  58454. this.updateFromDevice(pose);
  58455. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  58456. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  58457. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  58458. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  58459. if (this._mesh) {
  58460. this._mesh.position.copyFrom(this.devicePosition);
  58461. if (this._mesh.rotationQuaternion) {
  58462. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  58463. }
  58464. }
  58465. };
  58466. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  58467. if (poseData) {
  58468. this.rawPose = poseData;
  58469. if (poseData.position) {
  58470. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  58471. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  58472. this._deviceRoomPosition.z *= -1;
  58473. }
  58474. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  58475. this._calculatedPosition.addInPlace(this.position);
  58476. }
  58477. var pose = this.rawPose;
  58478. if (poseData.orientation && pose.orientation) {
  58479. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  58480. if (this._mesh) {
  58481. if (this._mesh.getScene().useRightHandedSystem) {
  58482. this._deviceRoomRotationQuaternion.z *= -1;
  58483. this._deviceRoomRotationQuaternion.w *= -1;
  58484. }
  58485. else {
  58486. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  58487. }
  58488. }
  58489. // if the camera is set, rotate to the camera's rotation
  58490. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  58491. }
  58492. }
  58493. };
  58494. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  58495. if (this._mesh) {
  58496. this._mesh.parent = null;
  58497. }
  58498. this._mesh = mesh;
  58499. if (this._poseControlledCamera) {
  58500. this._mesh.parent = this._poseControlledCamera;
  58501. }
  58502. if (!this._mesh.rotationQuaternion) {
  58503. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  58504. }
  58505. };
  58506. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  58507. this._poseControlledCamera = camera;
  58508. if (this._mesh) {
  58509. this._mesh.parent = this._poseControlledCamera;
  58510. }
  58511. };
  58512. PoseEnabledController.prototype.dispose = function () {
  58513. if (this._mesh) {
  58514. this._mesh.dispose();
  58515. }
  58516. this._mesh = null;
  58517. _super.prototype.dispose.call(this);
  58518. };
  58519. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  58520. get: function () {
  58521. return this._mesh;
  58522. },
  58523. enumerable: true,
  58524. configurable: true
  58525. });
  58526. PoseEnabledController.prototype.getForwardRay = function (length) {
  58527. if (length === void 0) { length = 100; }
  58528. if (!this.mesh) {
  58529. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  58530. }
  58531. var m = this.mesh.getWorldMatrix();
  58532. var origin = m.getTranslation();
  58533. var forward = new BABYLON.Vector3(0, 0, -1);
  58534. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  58535. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  58536. return new BABYLON.Ray(origin, direction, length);
  58537. };
  58538. return PoseEnabledController;
  58539. }(BABYLON.Gamepad));
  58540. BABYLON.PoseEnabledController = PoseEnabledController;
  58541. })(BABYLON || (BABYLON = {}));
  58542. //# sourceMappingURL=babylon.poseEnabledController.js.map
  58543. var BABYLON;
  58544. (function (BABYLON) {
  58545. var WebVRController = /** @class */ (function (_super) {
  58546. __extends(WebVRController, _super);
  58547. function WebVRController(vrGamepad) {
  58548. var _this = _super.call(this, vrGamepad) || this;
  58549. // Observables
  58550. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  58551. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  58552. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  58553. _this.onPadStateChangedObservable = new BABYLON.Observable();
  58554. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  58555. _this.pad = { x: 0, y: 0 };
  58556. // avoid GC, store state in a tmp object
  58557. _this._changes = {
  58558. pressChanged: false,
  58559. touchChanged: false,
  58560. valueChanged: false,
  58561. changed: false
  58562. };
  58563. _this._buttons = new Array(vrGamepad.buttons.length);
  58564. _this.hand = vrGamepad.hand;
  58565. return _this;
  58566. }
  58567. WebVRController.prototype.onButtonStateChange = function (callback) {
  58568. this._onButtonStateChange = callback;
  58569. };
  58570. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  58571. get: function () {
  58572. return this._defaultModel;
  58573. },
  58574. enumerable: true,
  58575. configurable: true
  58576. });
  58577. WebVRController.prototype.update = function () {
  58578. _super.prototype.update.call(this);
  58579. for (var index = 0; index < this._buttons.length; index++) {
  58580. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  58581. }
  58582. ;
  58583. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  58584. this.pad.x = this.leftStick.x;
  58585. this.pad.y = this.leftStick.y;
  58586. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  58587. }
  58588. };
  58589. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  58590. if (!newState) {
  58591. newState = {
  58592. pressed: false,
  58593. touched: false,
  58594. value: 0
  58595. };
  58596. }
  58597. if (!currentState) {
  58598. this._buttons[buttonIndex] = {
  58599. pressed: newState.pressed,
  58600. touched: newState.touched,
  58601. value: newState.value
  58602. };
  58603. return;
  58604. }
  58605. this._checkChanges(newState, currentState);
  58606. if (this._changes.changed) {
  58607. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  58608. this.handleButtonChange(buttonIndex, newState, this._changes);
  58609. }
  58610. this._buttons[buttonIndex].pressed = newState.pressed;
  58611. this._buttons[buttonIndex].touched = newState.touched;
  58612. // oculus triggers are never 0, thou not touched.
  58613. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  58614. };
  58615. WebVRController.prototype._checkChanges = function (newState, currentState) {
  58616. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  58617. this._changes.touchChanged = newState.touched !== currentState.touched;
  58618. this._changes.valueChanged = newState.value !== currentState.value;
  58619. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  58620. return this._changes;
  58621. };
  58622. WebVRController.prototype.dispose = function () {
  58623. _super.prototype.dispose.call(this);
  58624. this.onTriggerStateChangedObservable.clear();
  58625. this.onMainButtonStateChangedObservable.clear();
  58626. this.onSecondaryButtonStateChangedObservable.clear();
  58627. this.onPadStateChangedObservable.clear();
  58628. this.onPadValuesChangedObservable.clear();
  58629. };
  58630. return WebVRController;
  58631. }(BABYLON.PoseEnabledController));
  58632. BABYLON.WebVRController = WebVRController;
  58633. })(BABYLON || (BABYLON = {}));
  58634. //# sourceMappingURL=babylon.webVRController.js.map
  58635. var BABYLON;
  58636. (function (BABYLON) {
  58637. var OculusTouchController = /** @class */ (function (_super) {
  58638. __extends(OculusTouchController, _super);
  58639. function OculusTouchController(vrGamepad) {
  58640. var _this = _super.call(this, vrGamepad) || this;
  58641. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  58642. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  58643. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  58644. return _this;
  58645. }
  58646. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58647. var _this = this;
  58648. var meshName;
  58649. // Hand
  58650. if (this.hand === 'left') {
  58651. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  58652. }
  58653. else {
  58654. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  58655. }
  58656. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  58657. /*
  58658. Parent Mesh name: oculus_touch_left
  58659. - body
  58660. - trigger
  58661. - thumbstick
  58662. - grip
  58663. - button_y
  58664. - button_x
  58665. - button_enter
  58666. */
  58667. _this._defaultModel = newMeshes[1];
  58668. _this.attachToMesh(_this._defaultModel);
  58669. if (meshLoaded) {
  58670. meshLoaded(_this._defaultModel);
  58671. }
  58672. });
  58673. };
  58674. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  58675. // helper getters for left and right hand.
  58676. get: function () {
  58677. if (this.hand === 'right') {
  58678. return this.onMainButtonStateChangedObservable;
  58679. }
  58680. else {
  58681. throw new Error('No A button on left hand');
  58682. }
  58683. },
  58684. enumerable: true,
  58685. configurable: true
  58686. });
  58687. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  58688. get: function () {
  58689. if (this.hand === 'right') {
  58690. return this.onSecondaryButtonStateChangedObservable;
  58691. }
  58692. else {
  58693. throw new Error('No B button on left hand');
  58694. }
  58695. },
  58696. enumerable: true,
  58697. configurable: true
  58698. });
  58699. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  58700. get: function () {
  58701. if (this.hand === 'left') {
  58702. return this.onMainButtonStateChangedObservable;
  58703. }
  58704. else {
  58705. throw new Error('No X button on right hand');
  58706. }
  58707. },
  58708. enumerable: true,
  58709. configurable: true
  58710. });
  58711. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  58712. get: function () {
  58713. if (this.hand === 'left') {
  58714. return this.onSecondaryButtonStateChangedObservable;
  58715. }
  58716. else {
  58717. throw new Error('No Y button on right hand');
  58718. }
  58719. },
  58720. enumerable: true,
  58721. configurable: true
  58722. });
  58723. /*
  58724. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  58725. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  58726. 2) secondary trigger (same)
  58727. 3) A (right) X (left), touch, pressed = value
  58728. 4) B / Y
  58729. 5) thumb rest
  58730. */
  58731. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58732. var notifyObject = state; //{ state: state, changes: changes };
  58733. var triggerDirection = this.hand === 'right' ? -1 : 1;
  58734. switch (buttonIdx) {
  58735. case 0:
  58736. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58737. return;
  58738. case 1:// index trigger
  58739. if (this._defaultModel) {
  58740. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  58741. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  58742. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  58743. }
  58744. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58745. return;
  58746. case 2:// secondary trigger
  58747. if (this._defaultModel) {
  58748. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  58749. }
  58750. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  58751. return;
  58752. case 3:
  58753. if (this._defaultModel) {
  58754. if (notifyObject.pressed) {
  58755. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  58756. }
  58757. else {
  58758. (this._defaultModel.getChildren()[1]).position.y = 0;
  58759. }
  58760. }
  58761. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58762. return;
  58763. case 4:
  58764. if (this._defaultModel) {
  58765. if (notifyObject.pressed) {
  58766. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58767. }
  58768. else {
  58769. (this._defaultModel.getChildren()[2]).position.y = 0;
  58770. }
  58771. }
  58772. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58773. return;
  58774. case 5:
  58775. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  58776. return;
  58777. }
  58778. };
  58779. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  58780. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  58781. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  58782. return OculusTouchController;
  58783. }(BABYLON.WebVRController));
  58784. BABYLON.OculusTouchController = OculusTouchController;
  58785. })(BABYLON || (BABYLON = {}));
  58786. //# sourceMappingURL=babylon.oculusTouchController.js.map
  58787. var BABYLON;
  58788. (function (BABYLON) {
  58789. var ViveController = /** @class */ (function (_super) {
  58790. __extends(ViveController, _super);
  58791. function ViveController(vrGamepad) {
  58792. var _this = _super.call(this, vrGamepad) || this;
  58793. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  58794. _this._invertLeftStickY = true;
  58795. return _this;
  58796. }
  58797. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58798. var _this = this;
  58799. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  58800. /*
  58801. Parent Mesh name: ViveWand
  58802. - body
  58803. - r_gripper
  58804. - l_gripper
  58805. - menu_button
  58806. - system_button
  58807. - trackpad
  58808. - trigger
  58809. - LED
  58810. */
  58811. _this._defaultModel = newMeshes[1];
  58812. _this.attachToMesh(_this._defaultModel);
  58813. if (meshLoaded) {
  58814. meshLoaded(_this._defaultModel);
  58815. }
  58816. });
  58817. };
  58818. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  58819. get: function () {
  58820. return this.onMainButtonStateChangedObservable;
  58821. },
  58822. enumerable: true,
  58823. configurable: true
  58824. });
  58825. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  58826. get: function () {
  58827. return this.onMainButtonStateChangedObservable;
  58828. },
  58829. enumerable: true,
  58830. configurable: true
  58831. });
  58832. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  58833. get: function () {
  58834. return this.onSecondaryButtonStateChangedObservable;
  58835. },
  58836. enumerable: true,
  58837. configurable: true
  58838. });
  58839. /**
  58840. * Vive mapping:
  58841. * 0: touchpad
  58842. * 1: trigger
  58843. * 2: left AND right buttons
  58844. * 3: menu button
  58845. */
  58846. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58847. var notifyObject = state; //{ state: state, changes: changes };
  58848. switch (buttonIdx) {
  58849. case 0:
  58850. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58851. return;
  58852. case 1:// index trigger
  58853. if (this._defaultModel) {
  58854. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  58855. }
  58856. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58857. return;
  58858. case 2:// left AND right button
  58859. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58860. return;
  58861. case 3:
  58862. if (this._defaultModel) {
  58863. if (notifyObject.pressed) {
  58864. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58865. }
  58866. else {
  58867. (this._defaultModel.getChildren()[2]).position.y = 0;
  58868. }
  58869. }
  58870. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58871. return;
  58872. }
  58873. };
  58874. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  58875. ViveController.MODEL_FILENAME = 'wand.babylon';
  58876. return ViveController;
  58877. }(BABYLON.WebVRController));
  58878. BABYLON.ViveController = ViveController;
  58879. })(BABYLON || (BABYLON = {}));
  58880. //# sourceMappingURL=babylon.viveController.js.map
  58881. var BABYLON;
  58882. (function (BABYLON) {
  58883. var GenericController = /** @class */ (function (_super) {
  58884. __extends(GenericController, _super);
  58885. function GenericController(vrGamepad) {
  58886. return _super.call(this, vrGamepad) || this;
  58887. }
  58888. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58889. var _this = this;
  58890. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  58891. _this._defaultModel = newMeshes[1];
  58892. _this.attachToMesh(_this._defaultModel);
  58893. if (meshLoaded) {
  58894. meshLoaded(_this._defaultModel);
  58895. }
  58896. });
  58897. };
  58898. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58899. console.log("Button id: " + buttonIdx + "state: ");
  58900. console.dir(state);
  58901. };
  58902. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  58903. GenericController.MODEL_FILENAME = 'generic.babylon';
  58904. return GenericController;
  58905. }(BABYLON.WebVRController));
  58906. BABYLON.GenericController = GenericController;
  58907. })(BABYLON || (BABYLON = {}));
  58908. //# sourceMappingURL=babylon.genericController.js.map
  58909. var BABYLON;
  58910. (function (BABYLON) {
  58911. var LoadedMeshInfo = /** @class */ (function () {
  58912. function LoadedMeshInfo() {
  58913. this.buttonMeshes = {};
  58914. this.axisMeshes = {};
  58915. }
  58916. return LoadedMeshInfo;
  58917. }());
  58918. var WindowsMotionController = /** @class */ (function (_super) {
  58919. __extends(WindowsMotionController, _super);
  58920. function WindowsMotionController(vrGamepad) {
  58921. var _this = _super.call(this, vrGamepad) || this;
  58922. _this._mapping = {
  58923. // Semantic button names
  58924. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  58925. // A mapping of the button name to glTF model node name
  58926. // that should be transformed by button value.
  58927. buttonMeshNames: {
  58928. 'trigger': 'SELECT',
  58929. 'menu': 'MENU',
  58930. 'grip': 'GRASP',
  58931. 'thumbstick': 'THUMBSTICK_PRESS',
  58932. 'trackpad': 'TOUCHPAD_PRESS'
  58933. },
  58934. // This mapping is used to translate from the Motion Controller to Babylon semantics
  58935. buttonObservableNames: {
  58936. 'trigger': 'onTriggerStateChangedObservable',
  58937. 'menu': 'onSecondaryButtonStateChangedObservable',
  58938. 'grip': 'onMainButtonStateChangedObservable',
  58939. 'thumbstick': 'onPadStateChangedObservable',
  58940. 'trackpad': 'onTrackpadChangedObservable'
  58941. },
  58942. // A mapping of the axis name to glTF model node name
  58943. // that should be transformed by axis value.
  58944. // This array mirrors the browserGamepad.axes array, such that
  58945. // the mesh corresponding to axis 0 is in this array index 0.
  58946. axisMeshNames: [
  58947. 'THUMBSTICK_X',
  58948. 'THUMBSTICK_Y',
  58949. 'TOUCHPAD_TOUCH_X',
  58950. 'TOUCHPAD_TOUCH_Y'
  58951. ],
  58952. pointingPoseMeshName: 'POINTING_POSE'
  58953. };
  58954. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  58955. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  58956. _this.trackpad = { x: 0, y: 0 };
  58957. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  58958. _this._loadedMeshInfo = null;
  58959. return _this;
  58960. }
  58961. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  58962. get: function () {
  58963. return this.onTriggerStateChangedObservable;
  58964. },
  58965. enumerable: true,
  58966. configurable: true
  58967. });
  58968. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  58969. get: function () {
  58970. return this.onSecondaryButtonStateChangedObservable;
  58971. },
  58972. enumerable: true,
  58973. configurable: true
  58974. });
  58975. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  58976. get: function () {
  58977. return this.onMainButtonStateChangedObservable;
  58978. },
  58979. enumerable: true,
  58980. configurable: true
  58981. });
  58982. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  58983. get: function () {
  58984. return this.onPadStateChangedObservable;
  58985. },
  58986. enumerable: true,
  58987. configurable: true
  58988. });
  58989. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  58990. get: function () {
  58991. return this.onTrackpadChangedObservable;
  58992. },
  58993. enumerable: true,
  58994. configurable: true
  58995. });
  58996. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  58997. get: function () {
  58998. return this.onTrackpadValuesChangedObservable;
  58999. },
  59000. enumerable: true,
  59001. configurable: true
  59002. });
  59003. /**
  59004. * Called once per frame by the engine.
  59005. */
  59006. WindowsMotionController.prototype.update = function () {
  59007. _super.prototype.update.call(this);
  59008. // Only need to animate axes if there is a loaded mesh
  59009. if (this._loadedMeshInfo) {
  59010. if (this.browserGamepad.axes) {
  59011. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  59012. this.trackpad.x = this.browserGamepad["axes"][2];
  59013. this.trackpad.y = this.browserGamepad["axes"][3];
  59014. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  59015. }
  59016. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  59017. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  59018. }
  59019. }
  59020. }
  59021. };
  59022. /**
  59023. * Called once for each button that changed state since the last frame
  59024. * @param buttonIdx Which button index changed
  59025. * @param state New state of the button
  59026. * @param changes Which properties on the state changed since last frame
  59027. */
  59028. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  59029. var buttonName = this._mapping.buttons[buttonIdx];
  59030. if (!buttonName) {
  59031. return;
  59032. }
  59033. // Only emit events for buttons that we know how to map from index to name
  59034. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  59035. if (observable) {
  59036. observable.notifyObservers(state);
  59037. }
  59038. this.lerpButtonTransform(buttonName, state.value);
  59039. };
  59040. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  59041. // If there is no loaded mesh, there is nothing to transform.
  59042. if (!this._loadedMeshInfo) {
  59043. return;
  59044. }
  59045. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  59046. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  59047. return;
  59048. }
  59049. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  59050. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  59051. };
  59052. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  59053. if (!this._loadedMeshInfo) {
  59054. return;
  59055. }
  59056. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  59057. if (!meshInfo) {
  59058. return;
  59059. }
  59060. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  59061. return;
  59062. }
  59063. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  59064. var lerpValue = axisValue * 0.5 + 0.5;
  59065. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  59066. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  59067. };
  59068. /**
  59069. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  59070. * @param scene scene in which to add meshes
  59071. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  59072. */
  59073. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  59074. var _this = this;
  59075. if (forceDefault === void 0) { forceDefault = false; }
  59076. var path;
  59077. var filename;
  59078. // Checking if GLB loader is present
  59079. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  59080. // Determine the device specific folder based on the ID suffix
  59081. var device = 'default';
  59082. if (this.id && !forceDefault) {
  59083. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  59084. device = ((match && match[0]) || device);
  59085. }
  59086. // Hand
  59087. if (this.hand === 'left') {
  59088. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  59089. }
  59090. else {
  59091. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  59092. }
  59093. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  59094. }
  59095. else {
  59096. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  59097. path = BABYLON.GenericController.MODEL_BASE_URL;
  59098. filename = BABYLON.GenericController.MODEL_FILENAME;
  59099. }
  59100. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  59101. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  59102. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  59103. if (!_this._loadedMeshInfo) {
  59104. return;
  59105. }
  59106. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  59107. _this.attachToMesh(_this._defaultModel);
  59108. if (meshLoaded) {
  59109. meshLoaded(_this._defaultModel);
  59110. }
  59111. }, null, function (scene, message) {
  59112. BABYLON.Tools.Log(message);
  59113. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  59114. if (!forceDefault) {
  59115. _this.initControllerMesh(scene, meshLoaded, true);
  59116. }
  59117. });
  59118. };
  59119. /**
  59120. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  59121. * can be transformed by button presses and axes values, based on this._mapping.
  59122. *
  59123. * @param scene scene in which the meshes exist
  59124. * @param meshes list of meshes that make up the controller model to process
  59125. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  59126. */
  59127. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  59128. var loadedMeshInfo = null;
  59129. // Create a new mesh to contain the glTF hierarchy
  59130. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  59131. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  59132. var childMesh = null;
  59133. for (var i = 0; i < meshes.length; i++) {
  59134. var mesh = meshes[i];
  59135. if (!mesh.parent) {
  59136. // Exclude controller meshes from picking results
  59137. mesh.isPickable = false;
  59138. // Handle root node, attach to the new parentMesh
  59139. childMesh = mesh;
  59140. break;
  59141. }
  59142. }
  59143. if (childMesh) {
  59144. childMesh.setParent(parentMesh);
  59145. // Create our mesh info. Note that this method will always return non-null.
  59146. loadedMeshInfo = this.createMeshInfo(parentMesh);
  59147. }
  59148. else {
  59149. BABYLON.Tools.Warn('Could not find root node in model file.');
  59150. }
  59151. return loadedMeshInfo;
  59152. };
  59153. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  59154. var loadedMeshInfo = new LoadedMeshInfo();
  59155. var i;
  59156. loadedMeshInfo.rootNode = rootNode;
  59157. // Reset the caches
  59158. loadedMeshInfo.buttonMeshes = {};
  59159. loadedMeshInfo.axisMeshes = {};
  59160. // Button Meshes
  59161. for (i = 0; i < this._mapping.buttons.length; i++) {
  59162. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  59163. if (!buttonMeshName) {
  59164. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  59165. continue;
  59166. }
  59167. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  59168. if (!buttonMesh) {
  59169. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  59170. continue;
  59171. }
  59172. var buttonMeshInfo = {
  59173. index: i,
  59174. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  59175. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  59176. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  59177. };
  59178. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  59179. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  59180. }
  59181. else {
  59182. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  59183. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  59184. '(VALUE: ' + !!buttonMeshInfo.value +
  59185. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  59186. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  59187. ')');
  59188. }
  59189. }
  59190. // Axis Meshes
  59191. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  59192. var axisMeshName = this._mapping.axisMeshNames[i];
  59193. if (!axisMeshName) {
  59194. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  59195. continue;
  59196. }
  59197. var axisMesh = getChildByName(rootNode, axisMeshName);
  59198. if (!axisMesh) {
  59199. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  59200. continue;
  59201. }
  59202. var axisMeshInfo = {
  59203. index: i,
  59204. value: getImmediateChildByName(axisMesh, 'VALUE'),
  59205. min: getImmediateChildByName(axisMesh, 'MIN'),
  59206. max: getImmediateChildByName(axisMesh, 'MAX')
  59207. };
  59208. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  59209. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  59210. }
  59211. else {
  59212. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  59213. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  59214. '(VALUE: ' + !!axisMeshInfo.value +
  59215. ', MIN: ' + !!axisMeshInfo.min +
  59216. ', MAX:' + !!axisMeshInfo.max +
  59217. ')');
  59218. }
  59219. }
  59220. // Pointing Ray
  59221. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  59222. if (!loadedMeshInfo.pointingPoseNode) {
  59223. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  59224. }
  59225. return loadedMeshInfo;
  59226. // Look through all children recursively. This will return null if no mesh exists with the given name.
  59227. function getChildByName(node, name) {
  59228. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  59229. }
  59230. // Look through only immediate children. This will return null if no mesh exists with the given name.
  59231. function getImmediateChildByName(node, name) {
  59232. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  59233. }
  59234. };
  59235. WindowsMotionController.prototype.getForwardRay = function (length) {
  59236. if (length === void 0) { length = 100; }
  59237. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  59238. return _super.prototype.getForwardRay.call(this, length);
  59239. }
  59240. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  59241. var origin = m.getTranslation();
  59242. var forward = new BABYLON.Vector3(0, 0, -1);
  59243. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  59244. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  59245. return new BABYLON.Ray(origin, direction, length);
  59246. };
  59247. WindowsMotionController.prototype.dispose = function () {
  59248. _super.prototype.dispose.call(this);
  59249. this.onTrackpadChangedObservable.clear();
  59250. };
  59251. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  59252. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  59253. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  59254. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  59255. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  59256. return WindowsMotionController;
  59257. }(BABYLON.WebVRController));
  59258. BABYLON.WindowsMotionController = WindowsMotionController;
  59259. })(BABYLON || (BABYLON = {}));
  59260. //# sourceMappingURL=babylon.windowsMotionController.js.map
  59261. var BABYLON;
  59262. (function (BABYLON) {
  59263. var GearVRController = /** @class */ (function (_super) {
  59264. __extends(GearVRController, _super);
  59265. function GearVRController(vrGamepad) {
  59266. var _this = _super.call(this, vrGamepad) || this;
  59267. _this._buttonIndexToObservableNameMap = [
  59268. 'onTrackpadChangedObservable',
  59269. 'onTriggerStateChangedObservable' // Trigger
  59270. ];
  59271. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  59272. return _this;
  59273. }
  59274. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  59275. var _this = this;
  59276. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  59277. _this._defaultModel = newMeshes[1];
  59278. _this.attachToMesh(_this._defaultModel);
  59279. if (meshLoaded) {
  59280. meshLoaded(_this._defaultModel);
  59281. }
  59282. });
  59283. };
  59284. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  59285. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  59286. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  59287. // Only emit events for buttons that we know how to map from index to observable
  59288. var observable = this[observableName];
  59289. if (observable) {
  59290. observable.notifyObservers(state);
  59291. }
  59292. }
  59293. };
  59294. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  59295. GearVRController.MODEL_FILENAME = 'generic.babylon';
  59296. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  59297. return GearVRController;
  59298. }(BABYLON.WebVRController));
  59299. BABYLON.GearVRController = GearVRController;
  59300. })(BABYLON || (BABYLON = {}));
  59301. //# sourceMappingURL=babylon.gearVRController.js.map
  59302. var BABYLON;
  59303. (function (BABYLON) {
  59304. var FollowCamera = /** @class */ (function (_super) {
  59305. __extends(FollowCamera, _super);
  59306. function FollowCamera(name, position, scene, lockedTarget) {
  59307. if (lockedTarget === void 0) { lockedTarget = null; }
  59308. var _this = _super.call(this, name, position, scene) || this;
  59309. _this.radius = 12;
  59310. _this.rotationOffset = 0;
  59311. _this.heightOffset = 4;
  59312. _this.cameraAcceleration = 0.05;
  59313. _this.maxCameraSpeed = 20;
  59314. _this.lockedTarget = lockedTarget;
  59315. return _this;
  59316. }
  59317. FollowCamera.prototype.getRadians = function (degrees) {
  59318. return degrees * Math.PI / 180;
  59319. };
  59320. FollowCamera.prototype.follow = function (cameraTarget) {
  59321. if (!cameraTarget)
  59322. return;
  59323. var yRotation;
  59324. if (cameraTarget.rotationQuaternion) {
  59325. var rotMatrix = new BABYLON.Matrix();
  59326. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  59327. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  59328. }
  59329. else {
  59330. yRotation = cameraTarget.rotation.y;
  59331. }
  59332. var radians = this.getRadians(this.rotationOffset) + yRotation;
  59333. var targetPosition = cameraTarget.getAbsolutePosition();
  59334. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  59335. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  59336. var dx = targetX - this.position.x;
  59337. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  59338. var dz = (targetZ) - this.position.z;
  59339. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  59340. var vy = dy * this.cameraAcceleration;
  59341. var vz = dz * this.cameraAcceleration * 2;
  59342. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  59343. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59344. }
  59345. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  59346. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59347. }
  59348. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  59349. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59350. }
  59351. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  59352. this.setTarget(targetPosition);
  59353. };
  59354. FollowCamera.prototype._checkInputs = function () {
  59355. _super.prototype._checkInputs.call(this);
  59356. if (this.lockedTarget) {
  59357. this.follow(this.lockedTarget);
  59358. }
  59359. };
  59360. FollowCamera.prototype.getClassName = function () {
  59361. return "FollowCamera";
  59362. };
  59363. __decorate([
  59364. BABYLON.serialize()
  59365. ], FollowCamera.prototype, "radius", void 0);
  59366. __decorate([
  59367. BABYLON.serialize()
  59368. ], FollowCamera.prototype, "rotationOffset", void 0);
  59369. __decorate([
  59370. BABYLON.serialize()
  59371. ], FollowCamera.prototype, "heightOffset", void 0);
  59372. __decorate([
  59373. BABYLON.serialize()
  59374. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  59375. __decorate([
  59376. BABYLON.serialize()
  59377. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  59378. __decorate([
  59379. BABYLON.serializeAsMeshReference("lockedTargetId")
  59380. ], FollowCamera.prototype, "lockedTarget", void 0);
  59381. return FollowCamera;
  59382. }(BABYLON.TargetCamera));
  59383. BABYLON.FollowCamera = FollowCamera;
  59384. var ArcFollowCamera = /** @class */ (function (_super) {
  59385. __extends(ArcFollowCamera, _super);
  59386. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  59387. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  59388. _this.alpha = alpha;
  59389. _this.beta = beta;
  59390. _this.radius = radius;
  59391. _this.target = target;
  59392. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  59393. _this.follow();
  59394. return _this;
  59395. }
  59396. ArcFollowCamera.prototype.follow = function () {
  59397. if (!this.target) {
  59398. return;
  59399. }
  59400. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  59401. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  59402. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  59403. var targetPosition = this.target.getAbsolutePosition();
  59404. this.position = targetPosition.add(this._cartesianCoordinates);
  59405. this.setTarget(targetPosition);
  59406. };
  59407. ArcFollowCamera.prototype._checkInputs = function () {
  59408. _super.prototype._checkInputs.call(this);
  59409. this.follow();
  59410. };
  59411. ArcFollowCamera.prototype.getClassName = function () {
  59412. return "ArcFollowCamera";
  59413. };
  59414. return ArcFollowCamera;
  59415. }(BABYLON.TargetCamera));
  59416. BABYLON.ArcFollowCamera = ArcFollowCamera;
  59417. })(BABYLON || (BABYLON = {}));
  59418. //# sourceMappingURL=babylon.followCamera.js.map
  59419. var BABYLON;
  59420. (function (BABYLON) {
  59421. // We're mainly based on the logic defined into the FreeCamera code
  59422. var UniversalCamera = /** @class */ (function (_super) {
  59423. __extends(UniversalCamera, _super);
  59424. //-- end properties for backward compatibility for inputs
  59425. function UniversalCamera(name, position, scene) {
  59426. var _this = _super.call(this, name, position, scene) || this;
  59427. _this.inputs.addGamepad();
  59428. return _this;
  59429. }
  59430. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  59431. //-- Begin properties for backward compatibility for inputs
  59432. get: function () {
  59433. var gamepad = this.inputs.attached["gamepad"];
  59434. if (gamepad)
  59435. return gamepad.gamepadAngularSensibility;
  59436. return 0;
  59437. },
  59438. set: function (value) {
  59439. var gamepad = this.inputs.attached["gamepad"];
  59440. if (gamepad)
  59441. gamepad.gamepadAngularSensibility = value;
  59442. },
  59443. enumerable: true,
  59444. configurable: true
  59445. });
  59446. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  59447. get: function () {
  59448. var gamepad = this.inputs.attached["gamepad"];
  59449. if (gamepad)
  59450. return gamepad.gamepadMoveSensibility;
  59451. return 0;
  59452. },
  59453. set: function (value) {
  59454. var gamepad = this.inputs.attached["gamepad"];
  59455. if (gamepad)
  59456. gamepad.gamepadMoveSensibility = value;
  59457. },
  59458. enumerable: true,
  59459. configurable: true
  59460. });
  59461. UniversalCamera.prototype.getClassName = function () {
  59462. return "UniversalCamera";
  59463. };
  59464. return UniversalCamera;
  59465. }(BABYLON.TouchCamera));
  59466. BABYLON.UniversalCamera = UniversalCamera;
  59467. })(BABYLON || (BABYLON = {}));
  59468. //# sourceMappingURL=babylon.universalCamera.js.map
  59469. var BABYLON;
  59470. (function (BABYLON) {
  59471. // We're mainly based on the logic defined into the FreeCamera code
  59472. var GamepadCamera = /** @class */ (function (_super) {
  59473. __extends(GamepadCamera, _super);
  59474. //-- end properties for backward compatibility for inputs
  59475. function GamepadCamera(name, position, scene) {
  59476. return _super.call(this, name, position, scene) || this;
  59477. }
  59478. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  59479. //-- Begin properties for backward compatibility for inputs
  59480. get: function () {
  59481. var gamepad = this.inputs.attached["gamepad"];
  59482. if (gamepad)
  59483. return gamepad.gamepadAngularSensibility;
  59484. return 0;
  59485. },
  59486. set: function (value) {
  59487. var gamepad = this.inputs.attached["gamepad"];
  59488. if (gamepad)
  59489. gamepad.gamepadAngularSensibility = value;
  59490. },
  59491. enumerable: true,
  59492. configurable: true
  59493. });
  59494. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  59495. get: function () {
  59496. var gamepad = this.inputs.attached["gamepad"];
  59497. if (gamepad)
  59498. return gamepad.gamepadMoveSensibility;
  59499. return 0;
  59500. },
  59501. set: function (value) {
  59502. var gamepad = this.inputs.attached["gamepad"];
  59503. if (gamepad)
  59504. gamepad.gamepadMoveSensibility = value;
  59505. },
  59506. enumerable: true,
  59507. configurable: true
  59508. });
  59509. GamepadCamera.prototype.getClassName = function () {
  59510. return "GamepadCamera";
  59511. };
  59512. return GamepadCamera;
  59513. }(BABYLON.UniversalCamera));
  59514. BABYLON.GamepadCamera = GamepadCamera;
  59515. })(BABYLON || (BABYLON = {}));
  59516. //# sourceMappingURL=babylon.gamepadCamera.js.map
  59517. var BABYLON;
  59518. (function (BABYLON) {
  59519. var PostProcessRenderPipelineManager = /** @class */ (function () {
  59520. function PostProcessRenderPipelineManager() {
  59521. this._renderPipelines = {};
  59522. }
  59523. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  59524. this._renderPipelines[renderPipeline._name] = renderPipeline;
  59525. };
  59526. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  59527. if (unique === void 0) { unique = false; }
  59528. var renderPipeline = this._renderPipelines[renderPipelineName];
  59529. if (!renderPipeline) {
  59530. return;
  59531. }
  59532. renderPipeline._attachCameras(cameras, unique);
  59533. };
  59534. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  59535. var renderPipeline = this._renderPipelines[renderPipelineName];
  59536. if (!renderPipeline) {
  59537. return;
  59538. }
  59539. renderPipeline._detachCameras(cameras);
  59540. };
  59541. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  59542. var renderPipeline = this._renderPipelines[renderPipelineName];
  59543. if (!renderPipeline) {
  59544. return;
  59545. }
  59546. renderPipeline._enableEffect(renderEffectName, cameras);
  59547. };
  59548. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  59549. var renderPipeline = this._renderPipelines[renderPipelineName];
  59550. if (!renderPipeline) {
  59551. return;
  59552. }
  59553. renderPipeline._disableEffect(renderEffectName, cameras);
  59554. };
  59555. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  59556. var renderPipeline = this._renderPipelines[renderPipelineName];
  59557. if (!renderPipeline) {
  59558. return;
  59559. }
  59560. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  59561. };
  59562. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  59563. var renderPipeline = this._renderPipelines[renderPipelineName];
  59564. if (!renderPipeline) {
  59565. return;
  59566. }
  59567. renderPipeline._disableDisplayOnlyPass(cameras);
  59568. };
  59569. PostProcessRenderPipelineManager.prototype.update = function () {
  59570. for (var renderPipelineName in this._renderPipelines) {
  59571. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59572. var pipeline = this._renderPipelines[renderPipelineName];
  59573. if (!pipeline.isSupported) {
  59574. pipeline.dispose();
  59575. delete this._renderPipelines[renderPipelineName];
  59576. }
  59577. else {
  59578. pipeline._update();
  59579. }
  59580. }
  59581. }
  59582. };
  59583. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  59584. for (var renderPipelineName in this._renderPipelines) {
  59585. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59586. var pipeline = this._renderPipelines[renderPipelineName];
  59587. pipeline._rebuild();
  59588. }
  59589. }
  59590. };
  59591. PostProcessRenderPipelineManager.prototype.dispose = function () {
  59592. for (var renderPipelineName in this._renderPipelines) {
  59593. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59594. var pipeline = this._renderPipelines[renderPipelineName];
  59595. pipeline.dispose();
  59596. }
  59597. }
  59598. };
  59599. return PostProcessRenderPipelineManager;
  59600. }());
  59601. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  59602. })(BABYLON || (BABYLON = {}));
  59603. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  59604. var BABYLON;
  59605. (function (BABYLON) {
  59606. var PostProcessRenderPass = /** @class */ (function () {
  59607. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  59608. this._refCount = 0;
  59609. this._name = name;
  59610. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  59611. this.setRenderList(renderList);
  59612. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  59613. this._renderTexture.onAfterRenderObservable.add(afterRender);
  59614. this._scene = scene;
  59615. this._renderList = renderList;
  59616. }
  59617. // private
  59618. PostProcessRenderPass.prototype._incRefCount = function () {
  59619. if (this._refCount === 0) {
  59620. this._scene.customRenderTargets.push(this._renderTexture);
  59621. }
  59622. return ++this._refCount;
  59623. };
  59624. PostProcessRenderPass.prototype._decRefCount = function () {
  59625. this._refCount--;
  59626. if (this._refCount <= 0) {
  59627. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  59628. }
  59629. return this._refCount;
  59630. };
  59631. PostProcessRenderPass.prototype._update = function () {
  59632. this.setRenderList(this._renderList);
  59633. };
  59634. // public
  59635. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  59636. this._renderTexture.renderList = renderList;
  59637. };
  59638. PostProcessRenderPass.prototype.getRenderTexture = function () {
  59639. return this._renderTexture;
  59640. };
  59641. return PostProcessRenderPass;
  59642. }());
  59643. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  59644. })(BABYLON || (BABYLON = {}));
  59645. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  59646. var BABYLON;
  59647. (function (BABYLON) {
  59648. var PostProcessRenderEffect = /** @class */ (function () {
  59649. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  59650. this._name = name;
  59651. this._singleInstance = singleInstance || true;
  59652. this._getPostProcess = getPostProcess;
  59653. this._cameras = {};
  59654. this._indicesForCamera = {};
  59655. this._postProcesses = {};
  59656. this._renderPasses = {};
  59657. this._renderEffectAsPasses = {};
  59658. }
  59659. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  59660. get: function () {
  59661. for (var index in this._postProcesses) {
  59662. if (!this._postProcesses[index].isSupported) {
  59663. return false;
  59664. }
  59665. }
  59666. return true;
  59667. },
  59668. enumerable: true,
  59669. configurable: true
  59670. });
  59671. PostProcessRenderEffect.prototype._update = function () {
  59672. for (var renderPassName in this._renderPasses) {
  59673. this._renderPasses[renderPassName]._update();
  59674. }
  59675. };
  59676. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  59677. this._renderPasses[renderPass._name] = renderPass;
  59678. this._linkParameters();
  59679. };
  59680. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  59681. delete this._renderPasses[renderPass._name];
  59682. this._linkParameters();
  59683. };
  59684. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  59685. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  59686. this._linkParameters();
  59687. };
  59688. PostProcessRenderEffect.prototype.getPass = function (passName) {
  59689. for (var renderPassName in this._renderPasses) {
  59690. if (renderPassName === passName) {
  59691. return this._renderPasses[passName];
  59692. }
  59693. }
  59694. return null;
  59695. };
  59696. PostProcessRenderEffect.prototype.emptyPasses = function () {
  59697. this._renderPasses = {};
  59698. this._linkParameters();
  59699. };
  59700. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  59701. var cameraKey;
  59702. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59703. if (!cams) {
  59704. return;
  59705. }
  59706. for (var i = 0; i < cams.length; i++) {
  59707. var camera = cams[i];
  59708. var cameraName = camera.name;
  59709. if (this._singleInstance) {
  59710. cameraKey = 0;
  59711. }
  59712. else {
  59713. cameraKey = cameraName;
  59714. }
  59715. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  59716. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  59717. if (!this._indicesForCamera[cameraName]) {
  59718. this._indicesForCamera[cameraName] = [];
  59719. }
  59720. this._indicesForCamera[cameraName].push(index);
  59721. if (!this._cameras[cameraName]) {
  59722. this._cameras[cameraName] = camera;
  59723. }
  59724. for (var passName in this._renderPasses) {
  59725. this._renderPasses[passName]._incRefCount();
  59726. }
  59727. }
  59728. this._linkParameters();
  59729. };
  59730. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  59731. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59732. if (!cams) {
  59733. return;
  59734. }
  59735. for (var i = 0; i < cams.length; i++) {
  59736. var camera = cams[i];
  59737. var cameraName = camera.name;
  59738. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  59739. if (this._cameras[cameraName]) {
  59740. //this._indicesForCamera.splice(index, 1);
  59741. this._cameras[cameraName] = null;
  59742. }
  59743. for (var passName in this._renderPasses) {
  59744. this._renderPasses[passName]._decRefCount();
  59745. }
  59746. }
  59747. };
  59748. PostProcessRenderEffect.prototype._enable = function (cameras) {
  59749. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59750. if (!cams) {
  59751. return;
  59752. }
  59753. for (var i = 0; i < cams.length; i++) {
  59754. var camera = cams[i];
  59755. var cameraName = camera.name;
  59756. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  59757. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  59758. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  59759. }
  59760. }
  59761. for (var passName in this._renderPasses) {
  59762. this._renderPasses[passName]._incRefCount();
  59763. }
  59764. }
  59765. };
  59766. PostProcessRenderEffect.prototype._disable = function (cameras) {
  59767. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59768. if (!cams) {
  59769. return;
  59770. }
  59771. for (var i = 0; i < cams.length; i++) {
  59772. var camera = cams[i];
  59773. var cameraName = camera.Name;
  59774. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  59775. for (var passName in this._renderPasses) {
  59776. this._renderPasses[passName]._decRefCount();
  59777. }
  59778. }
  59779. };
  59780. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  59781. if (this._singleInstance) {
  59782. return this._postProcesses[0];
  59783. }
  59784. else {
  59785. if (!camera) {
  59786. return null;
  59787. }
  59788. return this._postProcesses[camera.name];
  59789. }
  59790. };
  59791. PostProcessRenderEffect.prototype._linkParameters = function () {
  59792. var _this = this;
  59793. for (var index in this._postProcesses) {
  59794. if (this.applyParameters) {
  59795. this.applyParameters(this._postProcesses[index]);
  59796. }
  59797. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  59798. _this._linkTextures(effect);
  59799. });
  59800. }
  59801. };
  59802. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  59803. for (var renderPassName in this._renderPasses) {
  59804. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  59805. }
  59806. for (var renderEffectName in this._renderEffectAsPasses) {
  59807. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  59808. }
  59809. };
  59810. return PostProcessRenderEffect;
  59811. }());
  59812. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  59813. })(BABYLON || (BABYLON = {}));
  59814. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  59815. var BABYLON;
  59816. (function (BABYLON) {
  59817. var PostProcessRenderPipeline = /** @class */ (function () {
  59818. function PostProcessRenderPipeline(engine, name) {
  59819. this._engine = engine;
  59820. this._name = name;
  59821. this._renderEffects = {};
  59822. this._renderEffectsForIsolatedPass = new Array();
  59823. this._cameras = [];
  59824. }
  59825. PostProcessRenderPipeline.prototype.getClassName = function () {
  59826. return "PostProcessRenderPipeline";
  59827. };
  59828. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  59829. get: function () {
  59830. for (var renderEffectName in this._renderEffects) {
  59831. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59832. if (!this._renderEffects[renderEffectName].isSupported) {
  59833. return false;
  59834. }
  59835. }
  59836. }
  59837. return true;
  59838. },
  59839. enumerable: true,
  59840. configurable: true
  59841. });
  59842. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  59843. this._renderEffects[renderEffect._name] = renderEffect;
  59844. };
  59845. // private
  59846. PostProcessRenderPipeline.prototype._rebuild = function () {
  59847. };
  59848. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  59849. var renderEffects = this._renderEffects[renderEffectName];
  59850. if (!renderEffects) {
  59851. return;
  59852. }
  59853. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  59854. };
  59855. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  59856. var renderEffects = this._renderEffects[renderEffectName];
  59857. if (!renderEffects) {
  59858. return;
  59859. }
  59860. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  59861. };
  59862. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  59863. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59864. if (!cams) {
  59865. return;
  59866. }
  59867. var indicesToDelete = [];
  59868. var i;
  59869. for (i = 0; i < cams.length; i++) {
  59870. var camera = cams[i];
  59871. var cameraName = camera.name;
  59872. if (this._cameras.indexOf(camera) === -1) {
  59873. this._cameras[cameraName] = camera;
  59874. }
  59875. else if (unique) {
  59876. indicesToDelete.push(i);
  59877. }
  59878. }
  59879. for (i = 0; i < indicesToDelete.length; i++) {
  59880. cameras.splice(indicesToDelete[i], 1);
  59881. }
  59882. for (var renderEffectName in this._renderEffects) {
  59883. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59884. this._renderEffects[renderEffectName]._attachCameras(cams);
  59885. }
  59886. }
  59887. };
  59888. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  59889. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59890. if (!cams) {
  59891. return;
  59892. }
  59893. for (var renderEffectName in this._renderEffects) {
  59894. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59895. this._renderEffects[renderEffectName]._detachCameras(cams);
  59896. }
  59897. }
  59898. for (var i = 0; i < cams.length; i++) {
  59899. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  59900. }
  59901. };
  59902. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  59903. var _this = this;
  59904. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59905. if (!cams) {
  59906. return;
  59907. }
  59908. var pass = null;
  59909. var renderEffectName;
  59910. for (renderEffectName in this._renderEffects) {
  59911. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59912. pass = this._renderEffects[renderEffectName].getPass(passName);
  59913. if (pass != null) {
  59914. break;
  59915. }
  59916. }
  59917. }
  59918. if (pass === null) {
  59919. return;
  59920. }
  59921. for (renderEffectName in this._renderEffects) {
  59922. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59923. this._renderEffects[renderEffectName]._disable(cams);
  59924. }
  59925. }
  59926. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  59927. for (var i = 0; i < cams.length; i++) {
  59928. var camera = cams[i];
  59929. var cameraName = camera.name;
  59930. 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); });
  59931. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  59932. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  59933. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  59934. }
  59935. };
  59936. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  59937. var _this = this;
  59938. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59939. if (!cams) {
  59940. return;
  59941. }
  59942. for (var i = 0; i < cams.length; i++) {
  59943. var camera = cams[i];
  59944. var cameraName = camera.name;
  59945. 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); });
  59946. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  59947. }
  59948. for (var renderEffectName in this._renderEffects) {
  59949. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59950. this._renderEffects[renderEffectName]._enable(cams);
  59951. }
  59952. }
  59953. };
  59954. PostProcessRenderPipeline.prototype._update = function () {
  59955. for (var renderEffectName in this._renderEffects) {
  59956. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59957. this._renderEffects[renderEffectName]._update();
  59958. }
  59959. }
  59960. for (var i = 0; i < this._cameras.length; i++) {
  59961. var cameraName = this._cameras[i].name;
  59962. if (this._renderEffectsForIsolatedPass[cameraName]) {
  59963. this._renderEffectsForIsolatedPass[cameraName]._update();
  59964. }
  59965. }
  59966. };
  59967. PostProcessRenderPipeline.prototype._reset = function () {
  59968. this._renderEffects = {};
  59969. this._renderEffectsForIsolatedPass = new Array();
  59970. };
  59971. PostProcessRenderPipeline.prototype.dispose = function () {
  59972. // Must be implemented by children
  59973. };
  59974. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  59975. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  59976. __decorate([
  59977. BABYLON.serialize()
  59978. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  59979. return PostProcessRenderPipeline;
  59980. }());
  59981. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  59982. })(BABYLON || (BABYLON = {}));
  59983. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  59984. var BABYLON;
  59985. (function (BABYLON) {
  59986. var DepthRenderer = /** @class */ (function () {
  59987. function DepthRenderer(scene, type) {
  59988. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  59989. var _this = this;
  59990. this._scene = scene;
  59991. var engine = scene.getEngine();
  59992. // Render target
  59993. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  59994. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59995. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59996. this._depthMap.refreshRate = 1;
  59997. this._depthMap.renderParticles = false;
  59998. this._depthMap.renderList = null;
  59999. // set default depth value to 1.0 (far away)
  60000. this._depthMap.onClearObservable.add(function (engine) {
  60001. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  60002. });
  60003. // Custom render function
  60004. var renderSubMesh = function (subMesh) {
  60005. var mesh = subMesh.getRenderingMesh();
  60006. var scene = _this._scene;
  60007. var engine = scene.getEngine();
  60008. var material = subMesh.getMaterial();
  60009. if (!material) {
  60010. return;
  60011. }
  60012. // Culling and reverse (right handed system)
  60013. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  60014. // Managing instances
  60015. var batch = mesh._getInstancesRenderList(subMesh._id);
  60016. if (batch.mustReturn) {
  60017. return;
  60018. }
  60019. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  60020. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  60021. engine.enableEffect(_this._effect);
  60022. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  60023. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  60024. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  60025. // Alpha test
  60026. if (material && material.needAlphaTesting()) {
  60027. var alphaTexture = material.getAlphaTestTexture();
  60028. if (alphaTexture) {
  60029. _this._effect.setTexture("diffuseSampler", alphaTexture);
  60030. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60031. }
  60032. }
  60033. // Bones
  60034. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60035. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60036. }
  60037. // Draw
  60038. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60039. }
  60040. };
  60041. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60042. var index;
  60043. if (depthOnlySubMeshes.length) {
  60044. engine.setColorWrite(false);
  60045. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60046. renderSubMesh(depthOnlySubMeshes.data[index]);
  60047. }
  60048. engine.setColorWrite(true);
  60049. }
  60050. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60051. renderSubMesh(opaqueSubMeshes.data[index]);
  60052. }
  60053. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60054. renderSubMesh(alphaTestSubMeshes.data[index]);
  60055. }
  60056. };
  60057. }
  60058. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  60059. var material = subMesh.getMaterial();
  60060. if (material.disableDepthWrite) {
  60061. return false;
  60062. }
  60063. var defines = [];
  60064. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60065. var mesh = subMesh.getMesh();
  60066. // Alpha test
  60067. if (material && material.needAlphaTesting()) {
  60068. defines.push("#define ALPHATEST");
  60069. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60070. attribs.push(BABYLON.VertexBuffer.UVKind);
  60071. defines.push("#define UV1");
  60072. }
  60073. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60074. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60075. defines.push("#define UV2");
  60076. }
  60077. }
  60078. // Bones
  60079. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60080. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60081. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60082. if (mesh.numBoneInfluencers > 4) {
  60083. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60084. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60085. }
  60086. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60087. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  60088. }
  60089. else {
  60090. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60091. }
  60092. // Instances
  60093. if (useInstances) {
  60094. defines.push("#define INSTANCES");
  60095. attribs.push("world0");
  60096. attribs.push("world1");
  60097. attribs.push("world2");
  60098. attribs.push("world3");
  60099. }
  60100. // Get correct effect
  60101. var join = defines.join("\n");
  60102. if (this._cachedDefines !== join) {
  60103. this._cachedDefines = join;
  60104. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  60105. }
  60106. return this._effect.isReady();
  60107. };
  60108. DepthRenderer.prototype.getDepthMap = function () {
  60109. return this._depthMap;
  60110. };
  60111. // Methods
  60112. DepthRenderer.prototype.dispose = function () {
  60113. this._depthMap.dispose();
  60114. };
  60115. return DepthRenderer;
  60116. }());
  60117. BABYLON.DepthRenderer = DepthRenderer;
  60118. })(BABYLON || (BABYLON = {}));
  60119. //# sourceMappingURL=babylon.depthRenderer.js.map
  60120. var BABYLON;
  60121. (function (BABYLON) {
  60122. var SSAORenderingPipeline = /** @class */ (function (_super) {
  60123. __extends(SSAORenderingPipeline, _super);
  60124. /**
  60125. * @constructor
  60126. * @param {string} name - The rendering pipeline name
  60127. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60128. * @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 }
  60129. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60130. */
  60131. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  60132. var _this = _super.call(this, scene.getEngine(), name) || this;
  60133. // Members
  60134. /**
  60135. * The PassPostProcess id in the pipeline that contains the original scene color
  60136. * @type {string}
  60137. */
  60138. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  60139. /**
  60140. * The SSAO PostProcess id in the pipeline
  60141. * @type {string}
  60142. */
  60143. _this.SSAORenderEffect = "SSAORenderEffect";
  60144. /**
  60145. * The horizontal blur PostProcess id in the pipeline
  60146. * @type {string}
  60147. */
  60148. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  60149. /**
  60150. * The vertical blur PostProcess id in the pipeline
  60151. * @type {string}
  60152. */
  60153. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  60154. /**
  60155. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  60156. * @type {string}
  60157. */
  60158. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  60159. /**
  60160. * The output strength of the SSAO post-process. Default value is 1.0.
  60161. * @type {number}
  60162. */
  60163. _this.totalStrength = 1.0;
  60164. /**
  60165. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  60166. * @type {number}
  60167. */
  60168. _this.radius = 0.0001;
  60169. /**
  60170. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  60171. * Must not be equal to fallOff and superior to fallOff.
  60172. * Default value is 0.975
  60173. * @type {number}
  60174. */
  60175. _this.area = 0.0075;
  60176. /**
  60177. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  60178. * Must not be equal to area and inferior to area.
  60179. * Default value is 0.0
  60180. * @type {number}
  60181. */
  60182. _this.fallOff = 0.000001;
  60183. /**
  60184. * The base color of the SSAO post-process
  60185. * The final result is "base + ssao" between [0, 1]
  60186. * @type {number}
  60187. */
  60188. _this.base = 0.5;
  60189. _this._firstUpdate = true;
  60190. _this._scene = scene;
  60191. // Set up assets
  60192. _this._createRandomTexture();
  60193. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  60194. var ssaoRatio = ratio.ssaoRatio || ratio;
  60195. var combineRatio = ratio.combineRatio || ratio;
  60196. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  60197. _this._createSSAOPostProcess(ssaoRatio);
  60198. _this._createBlurPostProcess(ssaoRatio);
  60199. _this._createSSAOCombinePostProcess(combineRatio);
  60200. // Set up pipeline
  60201. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  60202. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  60203. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  60204. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  60205. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  60206. // Finish
  60207. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60208. if (cameras)
  60209. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60210. return _this;
  60211. }
  60212. // Public Methods
  60213. /**
  60214. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  60215. */
  60216. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  60217. if (disableDepthRender === void 0) { disableDepthRender = false; }
  60218. for (var i = 0; i < this._scene.cameras.length; i++) {
  60219. var camera = this._scene.cameras[i];
  60220. this._originalColorPostProcess.dispose(camera);
  60221. this._ssaoPostProcess.dispose(camera);
  60222. this._blurHPostProcess.dispose(camera);
  60223. this._blurVPostProcess.dispose(camera);
  60224. this._ssaoCombinePostProcess.dispose(camera);
  60225. }
  60226. this._randomTexture.dispose();
  60227. if (disableDepthRender)
  60228. this._scene.disableDepthRenderer();
  60229. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60230. _super.prototype.dispose.call(this);
  60231. };
  60232. // Private Methods
  60233. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  60234. var _this = this;
  60235. var size = 16;
  60236. 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);
  60237. 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);
  60238. this._blurHPostProcess.onActivateObservable.add(function () {
  60239. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  60240. _this._blurHPostProcess.kernel = size * dw;
  60241. });
  60242. this._blurVPostProcess.onActivateObservable.add(function () {
  60243. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  60244. _this._blurVPostProcess.kernel = size * dw;
  60245. });
  60246. };
  60247. SSAORenderingPipeline.prototype._rebuild = function () {
  60248. this._firstUpdate = true;
  60249. _super.prototype._rebuild.call(this);
  60250. };
  60251. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  60252. var _this = this;
  60253. var numSamples = 16;
  60254. var sampleSphere = [
  60255. 0.5381, 0.1856, -0.4319,
  60256. 0.1379, 0.2486, 0.4430,
  60257. 0.3371, 0.5679, -0.0057,
  60258. -0.6999, -0.0451, -0.0019,
  60259. 0.0689, -0.1598, -0.8547,
  60260. 0.0560, 0.0069, -0.1843,
  60261. -0.0146, 0.1402, 0.0762,
  60262. 0.0100, -0.1924, -0.0344,
  60263. -0.3577, -0.5301, -0.4358,
  60264. -0.3169, 0.1063, 0.0158,
  60265. 0.0103, -0.5869, 0.0046,
  60266. -0.0897, -0.4940, 0.3287,
  60267. 0.7119, -0.0154, -0.0918,
  60268. -0.0533, 0.0596, -0.5411,
  60269. 0.0352, -0.0631, 0.5460,
  60270. -0.4776, 0.2847, -0.0271
  60271. ];
  60272. var samplesFactor = 1.0 / numSamples;
  60273. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  60274. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  60275. "area", "fallOff", "base", "range", "viewport"
  60276. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  60277. this._ssaoPostProcess.onApply = function (effect) {
  60278. if (_this._firstUpdate) {
  60279. effect.setArray3("sampleSphere", sampleSphere);
  60280. effect.setFloat("samplesFactor", samplesFactor);
  60281. effect.setFloat("randTextureTiles", 4.0);
  60282. }
  60283. effect.setFloat("totalStrength", _this.totalStrength);
  60284. effect.setFloat("radius", _this.radius);
  60285. effect.setFloat("area", _this.area);
  60286. effect.setFloat("fallOff", _this.fallOff);
  60287. effect.setFloat("base", _this.base);
  60288. effect.setTexture("textureSampler", _this._depthTexture);
  60289. effect.setTexture("randomSampler", _this._randomTexture);
  60290. };
  60291. };
  60292. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  60293. var _this = this;
  60294. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60295. this._ssaoCombinePostProcess.onApply = function (effect) {
  60296. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  60297. };
  60298. };
  60299. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  60300. var size = 512;
  60301. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60302. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60303. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60304. var context = this._randomTexture.getContext();
  60305. var rand = function (min, max) {
  60306. return Math.random() * (max - min) + min;
  60307. };
  60308. var randVector = BABYLON.Vector3.Zero();
  60309. for (var x = 0; x < size; x++) {
  60310. for (var y = 0; y < size; y++) {
  60311. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  60312. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  60313. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  60314. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  60315. context.fillRect(x, y, 1, 1);
  60316. }
  60317. }
  60318. this._randomTexture.update(false);
  60319. };
  60320. __decorate([
  60321. BABYLON.serialize()
  60322. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  60323. __decorate([
  60324. BABYLON.serialize()
  60325. ], SSAORenderingPipeline.prototype, "radius", void 0);
  60326. __decorate([
  60327. BABYLON.serialize()
  60328. ], SSAORenderingPipeline.prototype, "area", void 0);
  60329. __decorate([
  60330. BABYLON.serialize()
  60331. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  60332. __decorate([
  60333. BABYLON.serialize()
  60334. ], SSAORenderingPipeline.prototype, "base", void 0);
  60335. return SSAORenderingPipeline;
  60336. }(BABYLON.PostProcessRenderPipeline));
  60337. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  60338. })(BABYLON || (BABYLON = {}));
  60339. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  60340. var BABYLON;
  60341. (function (BABYLON) {
  60342. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  60343. __extends(SSAO2RenderingPipeline, _super);
  60344. /**
  60345. * @constructor
  60346. * @param {string} name - The rendering pipeline name
  60347. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60348. * @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 }
  60349. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60350. */
  60351. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  60352. var _this = _super.call(this, scene.getEngine(), name) || this;
  60353. // Members
  60354. /**
  60355. * The PassPostProcess id in the pipeline that contains the original scene color
  60356. * @type {string}
  60357. */
  60358. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  60359. /**
  60360. * The SSAO PostProcess id in the pipeline
  60361. * @type {string}
  60362. */
  60363. _this.SSAORenderEffect = "SSAORenderEffect";
  60364. /**
  60365. * The horizontal blur PostProcess id in the pipeline
  60366. * @type {string}
  60367. */
  60368. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  60369. /**
  60370. * The vertical blur PostProcess id in the pipeline
  60371. * @type {string}
  60372. */
  60373. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  60374. /**
  60375. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  60376. * @type {string}
  60377. */
  60378. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  60379. /**
  60380. * The output strength of the SSAO post-process. Default value is 1.0.
  60381. * @type {number}
  60382. */
  60383. _this.totalStrength = 1.0;
  60384. /**
  60385. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  60386. * @type {number}
  60387. */
  60388. _this.maxZ = 100.0;
  60389. /**
  60390. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  60391. * @type {number}
  60392. */
  60393. _this.minZAspect = 0.2;
  60394. /**
  60395. * Number of samples used for the SSAO calculations. Default value is 8
  60396. * @type {number}
  60397. */
  60398. _this._samples = 8;
  60399. /**
  60400. * Are we using bilateral blur ?
  60401. * @type {boolean}
  60402. */
  60403. _this._expensiveBlur = true;
  60404. /**
  60405. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  60406. * @type {number}
  60407. */
  60408. _this.radius = 2.0;
  60409. /**
  60410. * The base color of the SSAO post-process
  60411. * The final result is "base + ssao" between [0, 1]
  60412. * @type {number}
  60413. */
  60414. _this.base = 0.1;
  60415. _this._firstUpdate = true;
  60416. _this._scene = scene;
  60417. if (!_this.isSupported) {
  60418. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  60419. return _this;
  60420. }
  60421. var ssaoRatio = ratio.ssaoRatio || ratio;
  60422. var blurRatio = ratio.blurRatio || ratio;
  60423. // Set up assets
  60424. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  60425. _this._createRandomTexture();
  60426. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  60427. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  60428. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  60429. _this._createSSAOPostProcess(1.0);
  60430. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  60431. _this._createSSAOCombinePostProcess(blurRatio);
  60432. // Set up pipeline
  60433. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  60434. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  60435. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  60436. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  60437. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  60438. // Finish
  60439. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60440. if (cameras)
  60441. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60442. return _this;
  60443. }
  60444. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  60445. get: function () {
  60446. return this._samples;
  60447. },
  60448. set: function (n) {
  60449. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  60450. this._samples = n;
  60451. this._sampleSphere = this._generateHemisphere();
  60452. this._firstUpdate = true;
  60453. },
  60454. enumerable: true,
  60455. configurable: true
  60456. });
  60457. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  60458. get: function () {
  60459. return this._expensiveBlur;
  60460. },
  60461. set: function (b) {
  60462. 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"]);
  60463. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  60464. this._expensiveBlur = b;
  60465. this._firstUpdate = true;
  60466. },
  60467. enumerable: true,
  60468. configurable: true
  60469. });
  60470. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  60471. /**
  60472. * Support test.
  60473. * @type {boolean}
  60474. */
  60475. get: function () {
  60476. var engine = BABYLON.Engine.LastCreatedEngine;
  60477. if (!engine) {
  60478. return false;
  60479. }
  60480. return engine.getCaps().drawBuffersExtension;
  60481. },
  60482. enumerable: true,
  60483. configurable: true
  60484. });
  60485. // Public Methods
  60486. /**
  60487. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  60488. */
  60489. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  60490. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  60491. for (var i = 0; i < this._scene.cameras.length; i++) {
  60492. var camera = this._scene.cameras[i];
  60493. this._originalColorPostProcess.dispose(camera);
  60494. this._ssaoPostProcess.dispose(camera);
  60495. this._blurHPostProcess.dispose(camera);
  60496. this._blurVPostProcess.dispose(camera);
  60497. this._ssaoCombinePostProcess.dispose(camera);
  60498. }
  60499. this._randomTexture.dispose();
  60500. if (disableGeometryBufferRenderer)
  60501. this._scene.disableGeometryBufferRenderer();
  60502. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60503. _super.prototype.dispose.call(this);
  60504. };
  60505. // Private Methods
  60506. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  60507. var _this = this;
  60508. this._samplerOffsets = [];
  60509. var expensive = this.expensiveBlur;
  60510. for (var i = -8; i < 8; i++) {
  60511. this._samplerOffsets.push(i * 2 + 0.5);
  60512. }
  60513. 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");
  60514. this._blurHPostProcess.onApply = function (effect) {
  60515. if (!_this._scene.activeCamera) {
  60516. return;
  60517. }
  60518. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  60519. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60520. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60521. effect.setFloat("radius", _this.radius);
  60522. effect.setTexture("depthSampler", _this._depthTexture);
  60523. if (_this._firstUpdate) {
  60524. effect.setArray("samplerOffsets", _this._samplerOffsets);
  60525. }
  60526. };
  60527. 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");
  60528. this._blurVPostProcess.onApply = function (effect) {
  60529. if (!_this._scene.activeCamera) {
  60530. return;
  60531. }
  60532. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  60533. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60534. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60535. effect.setFloat("radius", _this.radius);
  60536. effect.setTexture("depthSampler", _this._depthTexture);
  60537. if (_this._firstUpdate) {
  60538. effect.setArray("samplerOffsets", _this._samplerOffsets);
  60539. _this._firstUpdate = false;
  60540. }
  60541. };
  60542. };
  60543. SSAO2RenderingPipeline.prototype._rebuild = function () {
  60544. this._firstUpdate = true;
  60545. _super.prototype._rebuild.call(this);
  60546. };
  60547. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  60548. var numSamples = this.samples;
  60549. var result = [];
  60550. var vector, scale;
  60551. var rand = function (min, max) {
  60552. return Math.random() * (max - min) + min;
  60553. };
  60554. var i = 0;
  60555. while (i < numSamples) {
  60556. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  60557. vector.normalize();
  60558. scale = i / numSamples;
  60559. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  60560. vector.scaleInPlace(scale);
  60561. result.push(vector.x, vector.y, vector.z);
  60562. i++;
  60563. }
  60564. return result;
  60565. };
  60566. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  60567. var _this = this;
  60568. var numSamples = this.samples;
  60569. this._sampleSphere = this._generateHemisphere();
  60570. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  60571. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  60572. "base", "range", "projection", "near", "far", "texelSize",
  60573. "xViewport", "yViewport", "maxZ", "minZAspect"
  60574. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  60575. this._ssaoPostProcess.onApply = function (effect) {
  60576. if (_this._firstUpdate) {
  60577. effect.setArray3("sampleSphere", _this._sampleSphere);
  60578. effect.setFloat("randTextureTiles", 4.0);
  60579. }
  60580. if (!_this._scene.activeCamera) {
  60581. return;
  60582. }
  60583. effect.setFloat("samplesFactor", 1 / _this.samples);
  60584. effect.setFloat("totalStrength", _this.totalStrength);
  60585. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  60586. effect.setFloat("radius", _this.radius);
  60587. effect.setFloat("maxZ", _this.maxZ);
  60588. effect.setFloat("minZAspect", _this.minZAspect);
  60589. effect.setFloat("base", _this.base);
  60590. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60591. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60592. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  60593. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  60594. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  60595. effect.setTexture("textureSampler", _this._depthTexture);
  60596. effect.setTexture("normalSampler", _this._normalTexture);
  60597. effect.setTexture("randomSampler", _this._randomTexture);
  60598. };
  60599. };
  60600. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  60601. var _this = this;
  60602. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60603. this._ssaoCombinePostProcess.onApply = function (effect) {
  60604. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  60605. };
  60606. };
  60607. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  60608. var size = 512;
  60609. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60610. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60611. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60612. var context = this._randomTexture.getContext();
  60613. var rand = function (min, max) {
  60614. return Math.random() * (max - min) + min;
  60615. };
  60616. var randVector = BABYLON.Vector3.Zero();
  60617. for (var x = 0; x < size; x++) {
  60618. for (var y = 0; y < size; y++) {
  60619. randVector.x = rand(0.0, 1.0);
  60620. randVector.y = rand(0.0, 1.0);
  60621. randVector.z = 0.0;
  60622. randVector.normalize();
  60623. randVector.scaleInPlace(255);
  60624. randVector.x = Math.floor(randVector.x);
  60625. randVector.y = Math.floor(randVector.y);
  60626. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  60627. context.fillRect(x, y, 1, 1);
  60628. }
  60629. }
  60630. this._randomTexture.update(false);
  60631. };
  60632. __decorate([
  60633. BABYLON.serialize()
  60634. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  60635. __decorate([
  60636. BABYLON.serialize()
  60637. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  60638. __decorate([
  60639. BABYLON.serialize()
  60640. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  60641. __decorate([
  60642. BABYLON.serialize("samples")
  60643. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  60644. __decorate([
  60645. BABYLON.serialize("expensiveBlur")
  60646. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  60647. __decorate([
  60648. BABYLON.serialize()
  60649. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  60650. __decorate([
  60651. BABYLON.serialize()
  60652. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  60653. return SSAO2RenderingPipeline;
  60654. }(BABYLON.PostProcessRenderPipeline));
  60655. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  60656. })(BABYLON || (BABYLON = {}));
  60657. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  60658. // BABYLON.JS Chromatic Aberration GLSL Shader
  60659. // Author: Olivier Guyot
  60660. // Separates very slightly R, G and B colors on the edges of the screen
  60661. // Inspired by Francois Tarlier & Martins Upitis
  60662. var BABYLON;
  60663. (function (BABYLON) {
  60664. var LensRenderingPipeline = /** @class */ (function (_super) {
  60665. __extends(LensRenderingPipeline, _super);
  60666. /**
  60667. * @constructor
  60668. *
  60669. * Effect parameters are as follow:
  60670. * {
  60671. * chromatic_aberration: number; // from 0 to x (1 for realism)
  60672. * edge_blur: number; // from 0 to x (1 for realism)
  60673. * distortion: number; // from 0 to x (1 for realism)
  60674. * grain_amount: number; // from 0 to 1
  60675. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  60676. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  60677. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  60678. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  60679. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  60680. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  60681. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  60682. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  60683. * }
  60684. * Note: if an effect parameter is unset, effect is disabled
  60685. *
  60686. * @param {string} name - The rendering pipeline name
  60687. * @param {object} parameters - An object containing all parameters (see above)
  60688. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60689. * @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)
  60690. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60691. */
  60692. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  60693. if (ratio === void 0) { ratio = 1.0; }
  60694. var _this = _super.call(this, scene.getEngine(), name) || this;
  60695. // Lens effects can be of the following:
  60696. // - chromatic aberration (slight shift of RGB colors)
  60697. // - blur on the edge of the lens
  60698. // - lens distortion
  60699. // - depth-of-field blur & highlights enhancing
  60700. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  60701. // - grain effect (noise or custom texture)
  60702. // Two additional texture samplers are needed:
  60703. // - depth map (for depth-of-field)
  60704. // - grain texture
  60705. /**
  60706. * The chromatic aberration PostProcess id in the pipeline
  60707. * @type {string}
  60708. */
  60709. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  60710. /**
  60711. * The highlights enhancing PostProcess id in the pipeline
  60712. * @type {string}
  60713. */
  60714. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  60715. /**
  60716. * The depth-of-field PostProcess id in the pipeline
  60717. * @type {string}
  60718. */
  60719. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  60720. _this._scene = scene;
  60721. // Fetch texture samplers
  60722. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  60723. if (parameters.grain_texture) {
  60724. _this._grainTexture = parameters.grain_texture;
  60725. }
  60726. else {
  60727. _this._createGrainTexture();
  60728. }
  60729. // save parameters
  60730. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  60731. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  60732. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  60733. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  60734. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  60735. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  60736. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  60737. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  60738. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  60739. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  60740. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  60741. // Create effects
  60742. _this._createChromaticAberrationPostProcess(ratio);
  60743. _this._createHighlightsPostProcess(ratio);
  60744. _this._createDepthOfFieldPostProcess(ratio / 4);
  60745. // Set up pipeline
  60746. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  60747. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  60748. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  60749. if (_this._highlightsGain === -1) {
  60750. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  60751. }
  60752. // Finish
  60753. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60754. if (cameras) {
  60755. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60756. }
  60757. return _this;
  60758. }
  60759. // public methods (self explanatory)
  60760. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  60761. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  60762. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  60763. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  60764. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  60765. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  60766. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  60767. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  60768. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  60769. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  60770. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  60771. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  60772. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  60773. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  60774. };
  60775. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  60776. this._highlightsPostProcess.updateEffect();
  60777. };
  60778. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  60779. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  60780. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  60781. this._highlightsGain = amount;
  60782. };
  60783. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  60784. if (this._highlightsGain === -1) {
  60785. this._highlightsGain = 1.0;
  60786. }
  60787. this._highlightsThreshold = amount;
  60788. };
  60789. LensRenderingPipeline.prototype.disableHighlights = function () {
  60790. this._highlightsGain = -1;
  60791. };
  60792. /**
  60793. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  60794. */
  60795. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  60796. if (disableDepthRender === void 0) { disableDepthRender = false; }
  60797. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60798. this._chromaticAberrationPostProcess = null;
  60799. this._highlightsPostProcess = null;
  60800. this._depthOfFieldPostProcess = null;
  60801. this._grainTexture.dispose();
  60802. if (disableDepthRender)
  60803. this._scene.disableDepthRenderer();
  60804. };
  60805. // colors shifting and distortion
  60806. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  60807. var _this = this;
  60808. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  60809. [], // samplers
  60810. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60811. this._chromaticAberrationPostProcess.onApply = function (effect) {
  60812. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  60813. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60814. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60815. };
  60816. };
  60817. // highlights enhancing
  60818. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  60819. var _this = this;
  60820. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  60821. [], // samplers
  60822. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  60823. this._highlightsPostProcess.onApply = function (effect) {
  60824. effect.setFloat('gain', _this._highlightsGain);
  60825. effect.setFloat('threshold', _this._highlightsThreshold);
  60826. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  60827. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60828. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60829. };
  60830. };
  60831. // colors shifting and distortion
  60832. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  60833. var _this = this;
  60834. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  60835. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  60836. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  60837. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60838. this._depthOfFieldPostProcess.onApply = function (effect) {
  60839. effect.setTexture("depthSampler", _this._depthTexture);
  60840. effect.setTexture("grainSampler", _this._grainTexture);
  60841. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  60842. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  60843. effect.setFloat('grain_amount', _this._grainAmount);
  60844. effect.setBool('blur_noise', _this._blurNoise);
  60845. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60846. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60847. effect.setFloat('distortion', _this._distortion);
  60848. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  60849. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  60850. effect.setFloat('aperture', _this._dofAperture);
  60851. effect.setFloat('darken', _this._dofDarken);
  60852. effect.setFloat('edge_blur', _this._edgeBlur);
  60853. effect.setBool('highlights', (_this._highlightsGain !== -1));
  60854. if (_this._scene.activeCamera) {
  60855. effect.setFloat('near', _this._scene.activeCamera.minZ);
  60856. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  60857. }
  60858. };
  60859. };
  60860. // creates a black and white random noise texture, 512x512
  60861. LensRenderingPipeline.prototype._createGrainTexture = function () {
  60862. var size = 512;
  60863. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60864. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60865. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60866. var context = this._grainTexture.getContext();
  60867. var rand = function (min, max) {
  60868. return Math.random() * (max - min) + min;
  60869. };
  60870. var value;
  60871. for (var x = 0; x < size; x++) {
  60872. for (var y = 0; y < size; y++) {
  60873. value = Math.floor(rand(0.42, 0.58) * 255);
  60874. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  60875. context.fillRect(x, y, 1, 1);
  60876. }
  60877. }
  60878. this._grainTexture.update(false);
  60879. };
  60880. return LensRenderingPipeline;
  60881. }(BABYLON.PostProcessRenderPipeline));
  60882. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  60883. })(BABYLON || (BABYLON = {}));
  60884. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  60885. var BABYLON;
  60886. (function (BABYLON) {
  60887. var StandardRenderingPipeline = /** @class */ (function (_super) {
  60888. __extends(StandardRenderingPipeline, _super);
  60889. /**
  60890. * @constructor
  60891. * @param {string} name - The rendering pipeline name
  60892. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60893. * @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)
  60894. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  60895. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60896. */
  60897. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  60898. if (originalPostProcess === void 0) { originalPostProcess = null; }
  60899. var _this = _super.call(this, scene.getEngine(), name) || this;
  60900. _this.downSampleX4PostProcess = null;
  60901. _this.brightPassPostProcess = null;
  60902. _this.blurHPostProcesses = [];
  60903. _this.blurVPostProcesses = [];
  60904. _this.textureAdderPostProcess = null;
  60905. _this.volumetricLightPostProcess = null;
  60906. _this.volumetricLightSmoothXPostProcess = null;
  60907. _this.volumetricLightSmoothYPostProcess = null;
  60908. _this.volumetricLightMergePostProces = null;
  60909. _this.volumetricLightFinalPostProcess = null;
  60910. _this.luminancePostProcess = null;
  60911. _this.luminanceDownSamplePostProcesses = [];
  60912. _this.hdrPostProcess = null;
  60913. _this.textureAdderFinalPostProcess = null;
  60914. _this.lensFlareFinalPostProcess = null;
  60915. _this.hdrFinalPostProcess = null;
  60916. _this.lensFlarePostProcess = null;
  60917. _this.lensFlareComposePostProcess = null;
  60918. _this.motionBlurPostProcess = null;
  60919. _this.depthOfFieldPostProcess = null;
  60920. // Values
  60921. _this.brightThreshold = 1.0;
  60922. _this.blurWidth = 512.0;
  60923. _this.horizontalBlur = false;
  60924. _this.exposure = 1.0;
  60925. _this.lensTexture = null;
  60926. _this.volumetricLightCoefficient = 0.2;
  60927. _this.volumetricLightPower = 4.0;
  60928. _this.volumetricLightBlurScale = 64.0;
  60929. _this.sourceLight = null;
  60930. _this.hdrMinimumLuminance = 1.0;
  60931. _this.hdrDecreaseRate = 0.5;
  60932. _this.hdrIncreaseRate = 0.5;
  60933. _this.lensColorTexture = null;
  60934. _this.lensFlareStrength = 20.0;
  60935. _this.lensFlareGhostDispersal = 1.4;
  60936. _this.lensFlareHaloWidth = 0.7;
  60937. _this.lensFlareDistortionStrength = 16.0;
  60938. _this.lensStarTexture = null;
  60939. _this.lensFlareDirtTexture = null;
  60940. _this.depthOfFieldDistance = 10.0;
  60941. _this.depthOfFieldBlurWidth = 64.0;
  60942. _this.motionStrength = 1.0;
  60943. // IAnimatable
  60944. _this.animations = [];
  60945. _this._currentDepthOfFieldSource = null;
  60946. _this._hdrCurrentLuminance = 1.0;
  60947. // Getters and setters
  60948. _this._bloomEnabled = true;
  60949. _this._depthOfFieldEnabled = false;
  60950. _this._vlsEnabled = false;
  60951. _this._lensFlareEnabled = false;
  60952. _this._hdrEnabled = false;
  60953. _this._motionBlurEnabled = false;
  60954. _this._motionBlurSamples = 64.0;
  60955. _this._volumetricLightStepsCount = 50.0;
  60956. _this._cameras = cameras || [];
  60957. // Initialize
  60958. _this._scene = scene;
  60959. _this._basePostProcess = originalPostProcess;
  60960. _this._ratio = ratio;
  60961. // Misc
  60962. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60963. // Finish
  60964. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60965. _this._buildPipeline();
  60966. return _this;
  60967. }
  60968. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  60969. get: function () {
  60970. return this._bloomEnabled;
  60971. },
  60972. set: function (enabled) {
  60973. if (this._bloomEnabled === enabled) {
  60974. return;
  60975. }
  60976. this._bloomEnabled = enabled;
  60977. this._buildPipeline();
  60978. },
  60979. enumerable: true,
  60980. configurable: true
  60981. });
  60982. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  60983. get: function () {
  60984. return this._depthOfFieldEnabled;
  60985. },
  60986. set: function (enabled) {
  60987. if (this._depthOfFieldEnabled === enabled) {
  60988. return;
  60989. }
  60990. this._depthOfFieldEnabled = enabled;
  60991. this._buildPipeline();
  60992. },
  60993. enumerable: true,
  60994. configurable: true
  60995. });
  60996. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  60997. get: function () {
  60998. return this._lensFlareEnabled;
  60999. },
  61000. set: function (enabled) {
  61001. if (this._lensFlareEnabled === enabled) {
  61002. return;
  61003. }
  61004. this._lensFlareEnabled = enabled;
  61005. this._buildPipeline();
  61006. },
  61007. enumerable: true,
  61008. configurable: true
  61009. });
  61010. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  61011. get: function () {
  61012. return this._hdrEnabled;
  61013. },
  61014. set: function (enabled) {
  61015. if (this._hdrEnabled === enabled) {
  61016. return;
  61017. }
  61018. this._hdrEnabled = enabled;
  61019. this._buildPipeline();
  61020. },
  61021. enumerable: true,
  61022. configurable: true
  61023. });
  61024. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  61025. get: function () {
  61026. return this._vlsEnabled;
  61027. },
  61028. set: function (enabled) {
  61029. if (this._vlsEnabled === enabled) {
  61030. return;
  61031. }
  61032. if (enabled) {
  61033. var geometry = this._scene.enableGeometryBufferRenderer();
  61034. if (!geometry) {
  61035. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  61036. return;
  61037. }
  61038. }
  61039. this._vlsEnabled = enabled;
  61040. this._buildPipeline();
  61041. },
  61042. enumerable: true,
  61043. configurable: true
  61044. });
  61045. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  61046. get: function () {
  61047. return this._motionBlurEnabled;
  61048. },
  61049. set: function (enabled) {
  61050. if (this._motionBlurEnabled === enabled) {
  61051. return;
  61052. }
  61053. this._motionBlurEnabled = enabled;
  61054. this._buildPipeline();
  61055. },
  61056. enumerable: true,
  61057. configurable: true
  61058. });
  61059. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  61060. get: function () {
  61061. return this._volumetricLightStepsCount;
  61062. },
  61063. set: function (count) {
  61064. if (this.volumetricLightPostProcess) {
  61065. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  61066. }
  61067. this._volumetricLightStepsCount = count;
  61068. },
  61069. enumerable: true,
  61070. configurable: true
  61071. });
  61072. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  61073. get: function () {
  61074. return this._motionBlurSamples;
  61075. },
  61076. set: function (samples) {
  61077. if (this.motionBlurPostProcess) {
  61078. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  61079. }
  61080. this._motionBlurSamples = samples;
  61081. },
  61082. enumerable: true,
  61083. configurable: true
  61084. });
  61085. StandardRenderingPipeline.prototype._buildPipeline = function () {
  61086. var _this = this;
  61087. var ratio = this._ratio;
  61088. var scene = this._scene;
  61089. this._disposePostProcesses();
  61090. this._reset();
  61091. // Create pass post-process
  61092. if (!this._basePostProcess) {
  61093. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  61094. this.originalPostProcess.onApply = function (effect) {
  61095. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  61096. };
  61097. }
  61098. else {
  61099. this.originalPostProcess = this._basePostProcess;
  61100. }
  61101. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  61102. this._currentDepthOfFieldSource = this.originalPostProcess;
  61103. if (this._vlsEnabled) {
  61104. // Create volumetric light
  61105. this._createVolumetricLightPostProcess(scene, ratio);
  61106. // Create volumetric light final post-process
  61107. 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);
  61108. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  61109. }
  61110. if (this._bloomEnabled) {
  61111. // Create down sample X4 post-process
  61112. this._createDownSampleX4PostProcess(scene, ratio / 2);
  61113. // Create bright pass post-process
  61114. this._createBrightPassPostProcess(scene, ratio / 2);
  61115. // Create gaussian blur post-processes (down sampling blurs)
  61116. this._createBlurPostProcesses(scene, ratio / 4, 1);
  61117. // Create texture adder post-process
  61118. this._createTextureAdderPostProcess(scene, ratio);
  61119. // Create depth-of-field source post-process
  61120. 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);
  61121. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  61122. }
  61123. if (this._lensFlareEnabled) {
  61124. // Create lens flare post-process
  61125. this._createLensFlarePostProcess(scene, ratio);
  61126. // Create depth-of-field source post-process post lens-flare and disable it now
  61127. 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);
  61128. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  61129. }
  61130. if (this._hdrEnabled) {
  61131. // Create luminance
  61132. this._createLuminancePostProcesses(scene, this._floatTextureType);
  61133. // Create HDR
  61134. this._createHdrPostProcess(scene, ratio);
  61135. // Create depth-of-field source post-process post hdr and disable it now
  61136. 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);
  61137. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  61138. }
  61139. if (this._depthOfFieldEnabled) {
  61140. // Create gaussian blur used by depth-of-field
  61141. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  61142. // Create depth-of-field post-process
  61143. this._createDepthOfFieldPostProcess(scene, ratio);
  61144. }
  61145. if (this._motionBlurEnabled) {
  61146. // Create motion blur post-process
  61147. this._createMotionBlurPostProcess(scene, ratio);
  61148. }
  61149. if (this._cameras !== null) {
  61150. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  61151. }
  61152. };
  61153. // Down Sample X4 Post-Processs
  61154. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  61155. var _this = this;
  61156. var downSampleX4Offsets = new Array(32);
  61157. 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);
  61158. this.downSampleX4PostProcess.onApply = function (effect) {
  61159. var id = 0;
  61160. var width = _this.downSampleX4PostProcess.width;
  61161. var height = _this.downSampleX4PostProcess.height;
  61162. for (var i = -2; i < 2; i++) {
  61163. for (var j = -2; j < 2; j++) {
  61164. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  61165. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  61166. id += 2;
  61167. }
  61168. }
  61169. effect.setArray2("dsOffsets", downSampleX4Offsets);
  61170. };
  61171. // Add to pipeline
  61172. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  61173. };
  61174. // Brightpass Post-Process
  61175. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  61176. var _this = this;
  61177. var brightOffsets = new Array(8);
  61178. 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);
  61179. this.brightPassPostProcess.onApply = function (effect) {
  61180. var sU = (1.0 / _this.brightPassPostProcess.width);
  61181. var sV = (1.0 / _this.brightPassPostProcess.height);
  61182. brightOffsets[0] = -0.5 * sU;
  61183. brightOffsets[1] = 0.5 * sV;
  61184. brightOffsets[2] = 0.5 * sU;
  61185. brightOffsets[3] = 0.5 * sV;
  61186. brightOffsets[4] = -0.5 * sU;
  61187. brightOffsets[5] = -0.5 * sV;
  61188. brightOffsets[6] = 0.5 * sU;
  61189. brightOffsets[7] = -0.5 * sV;
  61190. effect.setArray2("dsOffsets", brightOffsets);
  61191. effect.setFloat("brightThreshold", _this.brightThreshold);
  61192. };
  61193. // Add to pipeline
  61194. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  61195. };
  61196. // Create blur H&V post-processes
  61197. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  61198. var _this = this;
  61199. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  61200. var engine = scene.getEngine();
  61201. 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);
  61202. 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);
  61203. blurX.onActivateObservable.add(function () {
  61204. var dw = blurX.width / engine.getRenderWidth();
  61205. blurX.kernel = _this[blurWidthKey] * dw;
  61206. });
  61207. blurY.onActivateObservable.add(function () {
  61208. var dw = blurY.height / engine.getRenderHeight();
  61209. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  61210. });
  61211. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  61212. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  61213. this.blurHPostProcesses.push(blurX);
  61214. this.blurVPostProcesses.push(blurY);
  61215. };
  61216. // Create texture adder post-process
  61217. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  61218. var _this = this;
  61219. 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);
  61220. this.textureAdderPostProcess.onApply = function (effect) {
  61221. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  61222. effect.setTexture("lensSampler", _this.lensTexture);
  61223. effect.setFloat("exposure", _this.exposure);
  61224. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  61225. };
  61226. // Add to pipeline
  61227. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  61228. };
  61229. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  61230. var _this = this;
  61231. var geometryRenderer = scene.enableGeometryBufferRenderer();
  61232. geometryRenderer.enablePosition = true;
  61233. var geometry = geometryRenderer.getGBuffer();
  61234. // Base post-process
  61235. 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));
  61236. var depthValues = BABYLON.Vector2.Zero();
  61237. this.volumetricLightPostProcess.onApply = function (effect) {
  61238. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  61239. var generator = _this.sourceLight.getShadowGenerator();
  61240. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  61241. effect.setTexture("positionSampler", geometry.textures[2]);
  61242. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  61243. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  61244. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  61245. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  61246. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  61247. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  61248. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  61249. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  61250. effect.setVector2("depthValues", depthValues);
  61251. }
  61252. };
  61253. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  61254. // Smooth
  61255. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  61256. // Merge
  61257. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  61258. this.volumetricLightMergePostProces.onApply = function (effect) {
  61259. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  61260. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  61261. };
  61262. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  61263. };
  61264. // Create luminance
  61265. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  61266. var _this = this;
  61267. // Create luminance
  61268. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  61269. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  61270. var offsets = [];
  61271. this.luminancePostProcess.onApply = function (effect) {
  61272. var sU = (1.0 / _this.luminancePostProcess.width);
  61273. var sV = (1.0 / _this.luminancePostProcess.height);
  61274. offsets[0] = -0.5 * sU;
  61275. offsets[1] = 0.5 * sV;
  61276. offsets[2] = 0.5 * sU;
  61277. offsets[3] = 0.5 * sV;
  61278. offsets[4] = -0.5 * sU;
  61279. offsets[5] = -0.5 * sV;
  61280. offsets[6] = 0.5 * sU;
  61281. offsets[7] = -0.5 * sV;
  61282. effect.setArray2("lumOffsets", offsets);
  61283. };
  61284. // Add to pipeline
  61285. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  61286. // Create down sample luminance
  61287. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  61288. var size = Math.pow(3, i);
  61289. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  61290. if (i === 0) {
  61291. defines += "#define FINAL_DOWN_SAMPLER";
  61292. }
  61293. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  61294. this.luminanceDownSamplePostProcesses.push(postProcess);
  61295. }
  61296. // Create callbacks and add effects
  61297. var lastLuminance = this.luminancePostProcess;
  61298. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  61299. var downSampleOffsets = new Array(18);
  61300. pp.onApply = function (effect) {
  61301. if (!lastLuminance) {
  61302. return;
  61303. }
  61304. var id = 0;
  61305. for (var x = -1; x < 2; x++) {
  61306. for (var y = -1; y < 2; y++) {
  61307. downSampleOffsets[id] = x / lastLuminance.width;
  61308. downSampleOffsets[id + 1] = y / lastLuminance.height;
  61309. id += 2;
  61310. }
  61311. }
  61312. effect.setArray2("dsOffsets", downSampleOffsets);
  61313. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  61314. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  61315. lastLuminance = _this.luminancePostProcess;
  61316. }
  61317. else {
  61318. lastLuminance = pp;
  61319. }
  61320. };
  61321. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  61322. pp.onAfterRender = function (effect) {
  61323. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  61324. 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);
  61325. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  61326. };
  61327. }
  61328. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  61329. });
  61330. };
  61331. // Create HDR post-process
  61332. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  61333. var _this = this;
  61334. 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);
  61335. var outputLiminance = 1;
  61336. var time = 0;
  61337. var lastTime = 0;
  61338. this.hdrPostProcess.onApply = function (effect) {
  61339. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  61340. time += scene.getEngine().getDeltaTime();
  61341. if (outputLiminance < 0) {
  61342. outputLiminance = _this._hdrCurrentLuminance;
  61343. }
  61344. else {
  61345. var dt = (lastTime - time) / 1000.0;
  61346. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  61347. outputLiminance += _this.hdrDecreaseRate * dt;
  61348. }
  61349. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  61350. outputLiminance -= _this.hdrIncreaseRate * dt;
  61351. }
  61352. else {
  61353. outputLiminance = _this._hdrCurrentLuminance;
  61354. }
  61355. }
  61356. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  61357. effect.setFloat("averageLuminance", outputLiminance);
  61358. lastTime = time;
  61359. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  61360. };
  61361. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  61362. };
  61363. // Create lens flare post-process
  61364. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  61365. var _this = this;
  61366. 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);
  61367. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  61368. this._createBlurPostProcesses(scene, ratio / 4, 2);
  61369. 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);
  61370. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  61371. var resolution = new BABYLON.Vector2(0, 0);
  61372. // Lens flare
  61373. this.lensFlarePostProcess.onApply = function (effect) {
  61374. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  61375. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  61376. effect.setFloat("strength", _this.lensFlareStrength);
  61377. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  61378. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  61379. // Shift
  61380. resolution.x = _this.lensFlarePostProcess.width;
  61381. resolution.y = _this.lensFlarePostProcess.height;
  61382. effect.setVector2("resolution", resolution);
  61383. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  61384. };
  61385. // Compose
  61386. 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);
  61387. 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);
  61388. this.lensFlareComposePostProcess.onApply = function (effect) {
  61389. if (!_this._scene.activeCamera) {
  61390. return;
  61391. }
  61392. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  61393. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  61394. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  61395. // Lens start rotation matrix
  61396. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  61397. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  61398. 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));
  61399. camRot *= 4.0;
  61400. 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);
  61401. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  61402. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  61403. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  61404. };
  61405. };
  61406. // Create depth-of-field post-process
  61407. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  61408. var _this = this;
  61409. 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);
  61410. this.depthOfFieldPostProcess.onApply = function (effect) {
  61411. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  61412. effect.setTexture("depthSampler", _this._getDepthTexture());
  61413. effect.setFloat("distance", _this.depthOfFieldDistance);
  61414. };
  61415. // Add to pipeline
  61416. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  61417. };
  61418. // Create motion blur post-process
  61419. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  61420. var _this = this;
  61421. 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);
  61422. var motionScale = 0;
  61423. var prevViewProjection = BABYLON.Matrix.Identity();
  61424. var invViewProjection = BABYLON.Matrix.Identity();
  61425. var viewProjection = BABYLON.Matrix.Identity();
  61426. var screenSize = BABYLON.Vector2.Zero();
  61427. this.motionBlurPostProcess.onApply = function (effect) {
  61428. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  61429. viewProjection.invertToRef(invViewProjection);
  61430. effect.setMatrix("inverseViewProjection", invViewProjection);
  61431. effect.setMatrix("prevViewProjection", prevViewProjection);
  61432. prevViewProjection = viewProjection;
  61433. screenSize.x = _this.motionBlurPostProcess.width;
  61434. screenSize.y = _this.motionBlurPostProcess.height;
  61435. effect.setVector2("screenSize", screenSize);
  61436. motionScale = scene.getEngine().getFps() / 60.0;
  61437. effect.setFloat("motionScale", motionScale);
  61438. effect.setFloat("motionStrength", _this.motionStrength);
  61439. effect.setTexture("depthSampler", _this._getDepthTexture());
  61440. };
  61441. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  61442. };
  61443. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  61444. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  61445. var renderer = this._scene.enableGeometryBufferRenderer();
  61446. return renderer.getGBuffer().textures[0];
  61447. }
  61448. return this._scene.enableDepthRenderer().getDepthMap();
  61449. };
  61450. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  61451. for (var i = 0; i < this._cameras.length; i++) {
  61452. var camera = this._cameras[i];
  61453. if (this.originalPostProcess) {
  61454. this.originalPostProcess.dispose(camera);
  61455. }
  61456. if (this.downSampleX4PostProcess) {
  61457. this.downSampleX4PostProcess.dispose(camera);
  61458. }
  61459. if (this.brightPassPostProcess) {
  61460. this.brightPassPostProcess.dispose(camera);
  61461. }
  61462. if (this.textureAdderPostProcess) {
  61463. this.textureAdderPostProcess.dispose(camera);
  61464. }
  61465. if (this.textureAdderFinalPostProcess) {
  61466. this.textureAdderFinalPostProcess.dispose(camera);
  61467. }
  61468. if (this.volumetricLightPostProcess) {
  61469. this.volumetricLightPostProcess.dispose(camera);
  61470. }
  61471. if (this.volumetricLightSmoothXPostProcess) {
  61472. this.volumetricLightSmoothXPostProcess.dispose(camera);
  61473. }
  61474. if (this.volumetricLightSmoothYPostProcess) {
  61475. this.volumetricLightSmoothYPostProcess.dispose(camera);
  61476. }
  61477. if (this.volumetricLightMergePostProces) {
  61478. this.volumetricLightMergePostProces.dispose(camera);
  61479. }
  61480. if (this.volumetricLightFinalPostProcess) {
  61481. this.volumetricLightFinalPostProcess.dispose(camera);
  61482. }
  61483. if (this.lensFlarePostProcess) {
  61484. this.lensFlarePostProcess.dispose(camera);
  61485. }
  61486. if (this.lensFlareComposePostProcess) {
  61487. this.lensFlareComposePostProcess.dispose(camera);
  61488. }
  61489. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  61490. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  61491. }
  61492. if (this.luminancePostProcess) {
  61493. this.luminancePostProcess.dispose(camera);
  61494. }
  61495. if (this.hdrPostProcess) {
  61496. this.hdrPostProcess.dispose(camera);
  61497. }
  61498. if (this.hdrFinalPostProcess) {
  61499. this.hdrFinalPostProcess.dispose(camera);
  61500. }
  61501. if (this.depthOfFieldPostProcess) {
  61502. this.depthOfFieldPostProcess.dispose(camera);
  61503. }
  61504. if (this.motionBlurPostProcess) {
  61505. this.motionBlurPostProcess.dispose(camera);
  61506. }
  61507. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  61508. this.blurHPostProcesses[j].dispose(camera);
  61509. }
  61510. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  61511. this.blurVPostProcesses[j].dispose(camera);
  61512. }
  61513. }
  61514. this.originalPostProcess = null;
  61515. this.downSampleX4PostProcess = null;
  61516. this.brightPassPostProcess = null;
  61517. this.textureAdderPostProcess = null;
  61518. this.textureAdderFinalPostProcess = null;
  61519. this.volumetricLightPostProcess = null;
  61520. this.volumetricLightSmoothXPostProcess = null;
  61521. this.volumetricLightSmoothYPostProcess = null;
  61522. this.volumetricLightMergePostProces = null;
  61523. this.volumetricLightFinalPostProcess = null;
  61524. this.lensFlarePostProcess = null;
  61525. this.lensFlareComposePostProcess = null;
  61526. this.luminancePostProcess = null;
  61527. this.hdrPostProcess = null;
  61528. this.hdrFinalPostProcess = null;
  61529. this.depthOfFieldPostProcess = null;
  61530. this.motionBlurPostProcess = null;
  61531. this.luminanceDownSamplePostProcesses = [];
  61532. this.blurHPostProcesses = [];
  61533. this.blurVPostProcesses = [];
  61534. };
  61535. // Dispose
  61536. StandardRenderingPipeline.prototype.dispose = function () {
  61537. this._disposePostProcesses();
  61538. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61539. _super.prototype.dispose.call(this);
  61540. };
  61541. // Serialize rendering pipeline
  61542. StandardRenderingPipeline.prototype.serialize = function () {
  61543. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61544. serializationObject.customType = "StandardRenderingPipeline";
  61545. return serializationObject;
  61546. };
  61547. /**
  61548. * Static members
  61549. */
  61550. // Parse serialized pipeline
  61551. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61552. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  61553. };
  61554. // Luminance steps
  61555. StandardRenderingPipeline.LuminanceSteps = 6;
  61556. __decorate([
  61557. BABYLON.serialize()
  61558. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  61559. __decorate([
  61560. BABYLON.serialize()
  61561. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  61562. __decorate([
  61563. BABYLON.serialize()
  61564. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  61565. __decorate([
  61566. BABYLON.serialize()
  61567. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  61568. __decorate([
  61569. BABYLON.serializeAsTexture("lensTexture")
  61570. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  61571. __decorate([
  61572. BABYLON.serialize()
  61573. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  61574. __decorate([
  61575. BABYLON.serialize()
  61576. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  61577. __decorate([
  61578. BABYLON.serialize()
  61579. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  61580. __decorate([
  61581. BABYLON.serialize()
  61582. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  61583. __decorate([
  61584. BABYLON.serialize()
  61585. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  61586. __decorate([
  61587. BABYLON.serialize()
  61588. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  61589. __decorate([
  61590. BABYLON.serializeAsTexture("lensColorTexture")
  61591. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  61592. __decorate([
  61593. BABYLON.serialize()
  61594. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  61595. __decorate([
  61596. BABYLON.serialize()
  61597. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  61598. __decorate([
  61599. BABYLON.serialize()
  61600. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  61601. __decorate([
  61602. BABYLON.serialize()
  61603. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  61604. __decorate([
  61605. BABYLON.serializeAsTexture("lensStarTexture")
  61606. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  61607. __decorate([
  61608. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  61609. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  61610. __decorate([
  61611. BABYLON.serialize()
  61612. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  61613. __decorate([
  61614. BABYLON.serialize()
  61615. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  61616. __decorate([
  61617. BABYLON.serialize()
  61618. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  61619. __decorate([
  61620. BABYLON.serialize()
  61621. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  61622. __decorate([
  61623. BABYLON.serialize()
  61624. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  61625. __decorate([
  61626. BABYLON.serialize()
  61627. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  61628. __decorate([
  61629. BABYLON.serialize()
  61630. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  61631. __decorate([
  61632. BABYLON.serialize()
  61633. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  61634. __decorate([
  61635. BABYLON.serialize()
  61636. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  61637. __decorate([
  61638. BABYLON.serialize()
  61639. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  61640. __decorate([
  61641. BABYLON.serialize()
  61642. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  61643. __decorate([
  61644. BABYLON.serialize()
  61645. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  61646. return StandardRenderingPipeline;
  61647. }(BABYLON.PostProcessRenderPipeline));
  61648. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  61649. })(BABYLON || (BABYLON = {}));
  61650. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  61651. var BABYLON;
  61652. (function (BABYLON) {
  61653. var FxaaPostProcess = /** @class */ (function (_super) {
  61654. __extends(FxaaPostProcess, _super);
  61655. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  61656. if (camera === void 0) { camera = null; }
  61657. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61658. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  61659. _this.onApplyObservable.add(function (effect) {
  61660. var texelSize = _this.texelSize;
  61661. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  61662. });
  61663. return _this;
  61664. }
  61665. return FxaaPostProcess;
  61666. }(BABYLON.PostProcess));
  61667. BABYLON.FxaaPostProcess = FxaaPostProcess;
  61668. })(BABYLON || (BABYLON = {}));
  61669. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  61670. var BABYLON;
  61671. (function (BABYLON) {
  61672. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  61673. __extends(DefaultRenderingPipeline, _super);
  61674. /**
  61675. * @constructor
  61676. * @param {string} name - The rendering pipeline name
  61677. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61678. * @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)
  61679. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61680. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  61681. */
  61682. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  61683. if (automaticBuild === void 0) { automaticBuild = true; }
  61684. var _this = _super.call(this, scene.getEngine(), name) || this;
  61685. _this.PassPostProcessId = "PassPostProcessEffect";
  61686. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  61687. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  61688. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  61689. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  61690. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  61691. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  61692. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  61693. // IAnimatable
  61694. _this.animations = [];
  61695. // Values
  61696. _this._bloomEnabled = false;
  61697. _this._fxaaEnabled = false;
  61698. _this._imageProcessingEnabled = true;
  61699. _this._bloomScale = 0.6;
  61700. _this._buildAllowed = true;
  61701. /**
  61702. * Specifies the size of the bloom blur kernel, relative to the final output size
  61703. */
  61704. _this.bloomKernel = 64;
  61705. /**
  61706. * Specifies the weight of the bloom in the final rendering
  61707. */
  61708. _this._bloomWeight = 0.15;
  61709. _this._cameras = cameras || [];
  61710. _this._buildAllowed = automaticBuild;
  61711. // Initialize
  61712. _this._scene = scene;
  61713. var caps = _this._scene.getEngine().getCaps();
  61714. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  61715. // Misc
  61716. if (_this._hdr) {
  61717. if (caps.textureHalfFloatRender) {
  61718. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61719. }
  61720. else if (caps.textureFloatRender) {
  61721. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61722. }
  61723. }
  61724. else {
  61725. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61726. }
  61727. // Attach
  61728. scene.postProcessRenderPipelineManager.addPipeline(_this);
  61729. _this._buildPipeline();
  61730. return _this;
  61731. }
  61732. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  61733. get: function () {
  61734. return this._bloomWeight;
  61735. },
  61736. set: function (value) {
  61737. if (this._bloomWeight === value) {
  61738. return;
  61739. }
  61740. this._bloomWeight = value;
  61741. if (this._hdr && this.copyBack) {
  61742. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  61743. }
  61744. },
  61745. enumerable: true,
  61746. configurable: true
  61747. });
  61748. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  61749. get: function () {
  61750. return this._bloomScale;
  61751. },
  61752. set: function (value) {
  61753. if (this._bloomScale === value) {
  61754. return;
  61755. }
  61756. this._bloomScale = value;
  61757. this._buildPipeline();
  61758. },
  61759. enumerable: true,
  61760. configurable: true
  61761. });
  61762. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  61763. get: function () {
  61764. return this._bloomEnabled;
  61765. },
  61766. set: function (enabled) {
  61767. if (this._bloomEnabled === enabled) {
  61768. return;
  61769. }
  61770. this._bloomEnabled = enabled;
  61771. this._buildPipeline();
  61772. },
  61773. enumerable: true,
  61774. configurable: true
  61775. });
  61776. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  61777. get: function () {
  61778. return this._fxaaEnabled;
  61779. },
  61780. set: function (enabled) {
  61781. if (this._fxaaEnabled === enabled) {
  61782. return;
  61783. }
  61784. this._fxaaEnabled = enabled;
  61785. this._buildPipeline();
  61786. },
  61787. enumerable: true,
  61788. configurable: true
  61789. });
  61790. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  61791. get: function () {
  61792. return this._imageProcessingEnabled;
  61793. },
  61794. set: function (enabled) {
  61795. if (this._imageProcessingEnabled === enabled) {
  61796. return;
  61797. }
  61798. this._imageProcessingEnabled = enabled;
  61799. this._buildPipeline();
  61800. },
  61801. enumerable: true,
  61802. configurable: true
  61803. });
  61804. /**
  61805. * Force the compilation of the entire pipeline.
  61806. */
  61807. DefaultRenderingPipeline.prototype.prepare = function () {
  61808. var previousState = this._buildAllowed;
  61809. this._buildAllowed = true;
  61810. this._buildPipeline();
  61811. this._buildAllowed = previousState;
  61812. };
  61813. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  61814. var _this = this;
  61815. if (!this._buildAllowed) {
  61816. return;
  61817. }
  61818. var engine = this._scene.getEngine();
  61819. this._disposePostProcesses();
  61820. this._reset();
  61821. if (this.bloomEnabled) {
  61822. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61823. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  61824. if (!this._hdr) {
  61825. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61826. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  61827. this.highlights.autoClear = false;
  61828. this.highlights.alwaysForcePOT = true;
  61829. }
  61830. 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);
  61831. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  61832. this.blurX.alwaysForcePOT = true;
  61833. this.blurX.autoClear = false;
  61834. this.blurX.onActivateObservable.add(function () {
  61835. var dw = _this.blurX.width / engine.getRenderWidth(true);
  61836. _this.blurX.kernel = _this.bloomKernel * dw;
  61837. });
  61838. 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);
  61839. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  61840. this.blurY.alwaysForcePOT = true;
  61841. this.blurY.autoClear = false;
  61842. this.blurY.onActivateObservable.add(function () {
  61843. var dh = _this.blurY.height / engine.getRenderHeight(true);
  61844. _this.blurY.kernel = _this.bloomKernel * dh;
  61845. });
  61846. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61847. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  61848. this.copyBack.alwaysForcePOT = true;
  61849. if (this._hdr) {
  61850. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  61851. var w = this.bloomWeight;
  61852. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  61853. }
  61854. else {
  61855. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  61856. }
  61857. this.copyBack.autoClear = false;
  61858. }
  61859. if (this._imageProcessingEnabled) {
  61860. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61861. if (this._hdr) {
  61862. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  61863. }
  61864. else {
  61865. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  61866. }
  61867. }
  61868. if (this.fxaaEnabled) {
  61869. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61870. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  61871. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61872. }
  61873. else if (this._hdr && this.imageProcessing) {
  61874. this.finalMerge = this.imageProcessing;
  61875. }
  61876. else {
  61877. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61878. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  61879. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61880. }
  61881. if (this.bloomEnabled) {
  61882. if (this._hdr) {
  61883. this.copyBack.shareOutputWith(this.blurX);
  61884. if (this.imageProcessing) {
  61885. this.imageProcessing.shareOutputWith(this.pass);
  61886. this.imageProcessing.autoClear = false;
  61887. }
  61888. else if (this.fxaa) {
  61889. this.fxaa.shareOutputWith(this.pass);
  61890. }
  61891. else {
  61892. this.finalMerge.shareOutputWith(this.pass);
  61893. }
  61894. }
  61895. else {
  61896. if (this.fxaa) {
  61897. this.fxaa.shareOutputWith(this.pass);
  61898. }
  61899. else {
  61900. this.finalMerge.shareOutputWith(this.pass);
  61901. }
  61902. }
  61903. }
  61904. if (this._cameras !== null) {
  61905. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  61906. }
  61907. };
  61908. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  61909. for (var i = 0; i < this._cameras.length; i++) {
  61910. var camera = this._cameras[i];
  61911. if (this.pass) {
  61912. this.pass.dispose(camera);
  61913. }
  61914. if (this.highlights) {
  61915. this.highlights.dispose(camera);
  61916. }
  61917. if (this.blurX) {
  61918. this.blurX.dispose(camera);
  61919. }
  61920. if (this.blurY) {
  61921. this.blurY.dispose(camera);
  61922. }
  61923. if (this.copyBack) {
  61924. this.copyBack.dispose(camera);
  61925. }
  61926. if (this.imageProcessing) {
  61927. this.imageProcessing.dispose(camera);
  61928. }
  61929. if (this.fxaa) {
  61930. this.fxaa.dispose(camera);
  61931. }
  61932. if (this.finalMerge) {
  61933. this.finalMerge.dispose(camera);
  61934. }
  61935. }
  61936. this.pass = null;
  61937. this.highlights = null;
  61938. this.blurX = null;
  61939. this.blurY = null;
  61940. this.copyBack = null;
  61941. this.imageProcessing = null;
  61942. this.fxaa = null;
  61943. this.finalMerge = null;
  61944. };
  61945. // Dispose
  61946. DefaultRenderingPipeline.prototype.dispose = function () {
  61947. this._disposePostProcesses();
  61948. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61949. _super.prototype.dispose.call(this);
  61950. };
  61951. // Serialize rendering pipeline
  61952. DefaultRenderingPipeline.prototype.serialize = function () {
  61953. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61954. serializationObject.customType = "DefaultRenderingPipeline";
  61955. return serializationObject;
  61956. };
  61957. // Parse serialized pipeline
  61958. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61959. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  61960. };
  61961. __decorate([
  61962. BABYLON.serialize()
  61963. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  61964. __decorate([
  61965. BABYLON.serialize()
  61966. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  61967. __decorate([
  61968. BABYLON.serialize()
  61969. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  61970. __decorate([
  61971. BABYLON.serialize()
  61972. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  61973. __decorate([
  61974. BABYLON.serialize()
  61975. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  61976. __decorate([
  61977. BABYLON.serialize()
  61978. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  61979. __decorate([
  61980. BABYLON.serialize()
  61981. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  61982. __decorate([
  61983. BABYLON.serialize()
  61984. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  61985. return DefaultRenderingPipeline;
  61986. }(BABYLON.PostProcessRenderPipeline));
  61987. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  61988. })(BABYLON || (BABYLON = {}));
  61989. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  61990. var BABYLON;
  61991. (function (BABYLON) {
  61992. var GeometryBufferRenderer = /** @class */ (function () {
  61993. function GeometryBufferRenderer(scene, ratio) {
  61994. if (ratio === void 0) { ratio = 1; }
  61995. this._enablePosition = false;
  61996. this._scene = scene;
  61997. this._ratio = ratio;
  61998. // Render target
  61999. this._createRenderTargets();
  62000. }
  62001. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  62002. set: function (meshes) {
  62003. this._multiRenderTarget.renderList = meshes;
  62004. },
  62005. enumerable: true,
  62006. configurable: true
  62007. });
  62008. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  62009. get: function () {
  62010. return this._multiRenderTarget.isSupported;
  62011. },
  62012. enumerable: true,
  62013. configurable: true
  62014. });
  62015. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  62016. get: function () {
  62017. return this._enablePosition;
  62018. },
  62019. set: function (enable) {
  62020. this._enablePosition = enable;
  62021. this.dispose();
  62022. this._createRenderTargets();
  62023. },
  62024. enumerable: true,
  62025. configurable: true
  62026. });
  62027. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  62028. var material = subMesh.getMaterial();
  62029. if (material && material.disableDepthWrite) {
  62030. return false;
  62031. }
  62032. var defines = [];
  62033. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  62034. var mesh = subMesh.getMesh();
  62035. // Alpha test
  62036. if (material && material.needAlphaTesting()) {
  62037. defines.push("#define ALPHATEST");
  62038. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62039. attribs.push(BABYLON.VertexBuffer.UVKind);
  62040. defines.push("#define UV1");
  62041. }
  62042. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62043. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62044. defines.push("#define UV2");
  62045. }
  62046. }
  62047. // Buffers
  62048. if (this._enablePosition) {
  62049. defines.push("#define POSITION");
  62050. }
  62051. // Bones
  62052. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62053. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62054. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62055. if (mesh.numBoneInfluencers > 4) {
  62056. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62057. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62058. }
  62059. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62060. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  62061. }
  62062. else {
  62063. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62064. }
  62065. // Instances
  62066. if (useInstances) {
  62067. defines.push("#define INSTANCES");
  62068. attribs.push("world0");
  62069. attribs.push("world1");
  62070. attribs.push("world2");
  62071. attribs.push("world3");
  62072. }
  62073. // Get correct effect
  62074. var join = defines.join("\n");
  62075. if (this._cachedDefines !== join) {
  62076. this._cachedDefines = join;
  62077. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  62078. }
  62079. return this._effect.isReady();
  62080. };
  62081. GeometryBufferRenderer.prototype.getGBuffer = function () {
  62082. return this._multiRenderTarget;
  62083. };
  62084. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  62085. get: function () {
  62086. return this._multiRenderTarget.samples;
  62087. },
  62088. set: function (value) {
  62089. this._multiRenderTarget.samples = value;
  62090. },
  62091. enumerable: true,
  62092. configurable: true
  62093. });
  62094. // Methods
  62095. GeometryBufferRenderer.prototype.dispose = function () {
  62096. this.getGBuffer().dispose();
  62097. };
  62098. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  62099. var _this = this;
  62100. var engine = this._scene.getEngine();
  62101. var count = this._enablePosition ? 3 : 2;
  62102. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON.Engine.TEXTURETYPE_FLOAT });
  62103. if (!this.isSupported) {
  62104. return;
  62105. }
  62106. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62107. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62108. this._multiRenderTarget.refreshRate = 1;
  62109. this._multiRenderTarget.renderParticles = false;
  62110. this._multiRenderTarget.renderList = null;
  62111. // set default depth value to 1.0 (far away)
  62112. this._multiRenderTarget.onClearObservable.add(function (engine) {
  62113. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  62114. });
  62115. // Custom render function
  62116. var renderSubMesh = function (subMesh) {
  62117. var mesh = subMesh.getRenderingMesh();
  62118. var scene = _this._scene;
  62119. var engine = scene.getEngine();
  62120. var material = subMesh.getMaterial();
  62121. if (!material) {
  62122. return;
  62123. }
  62124. // Culling
  62125. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  62126. // Managing instances
  62127. var batch = mesh._getInstancesRenderList(subMesh._id);
  62128. if (batch.mustReturn) {
  62129. return;
  62130. }
  62131. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  62132. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  62133. engine.enableEffect(_this._effect);
  62134. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  62135. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  62136. _this._effect.setMatrix("view", scene.getViewMatrix());
  62137. // Alpha test
  62138. if (material && material.needAlphaTesting()) {
  62139. var alphaTexture = material.getAlphaTestTexture();
  62140. if (alphaTexture) {
  62141. _this._effect.setTexture("diffuseSampler", alphaTexture);
  62142. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  62143. }
  62144. }
  62145. // Bones
  62146. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62147. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  62148. }
  62149. // Draw
  62150. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  62151. }
  62152. };
  62153. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62154. var index;
  62155. if (depthOnlySubMeshes.length) {
  62156. engine.setColorWrite(false);
  62157. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62158. renderSubMesh(depthOnlySubMeshes.data[index]);
  62159. }
  62160. engine.setColorWrite(true);
  62161. }
  62162. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62163. renderSubMesh(opaqueSubMeshes.data[index]);
  62164. }
  62165. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62166. renderSubMesh(alphaTestSubMeshes.data[index]);
  62167. }
  62168. };
  62169. };
  62170. return GeometryBufferRenderer;
  62171. }());
  62172. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  62173. })(BABYLON || (BABYLON = {}));
  62174. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  62175. var BABYLON;
  62176. (function (BABYLON) {
  62177. var RefractionPostProcess = /** @class */ (function (_super) {
  62178. __extends(RefractionPostProcess, _super);
  62179. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  62180. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  62181. _this.color = color;
  62182. _this.depth = depth;
  62183. _this.colorLevel = colorLevel;
  62184. _this.onActivateObservable.add(function (cam) {
  62185. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  62186. });
  62187. _this.onApplyObservable.add(function (effect) {
  62188. effect.setColor3("baseColor", _this.color);
  62189. effect.setFloat("depth", _this.depth);
  62190. effect.setFloat("colorLevel", _this.colorLevel);
  62191. effect.setTexture("refractionSampler", _this._refRexture);
  62192. });
  62193. return _this;
  62194. }
  62195. // Methods
  62196. RefractionPostProcess.prototype.dispose = function (camera) {
  62197. if (this._refRexture) {
  62198. this._refRexture.dispose();
  62199. }
  62200. _super.prototype.dispose.call(this, camera);
  62201. };
  62202. return RefractionPostProcess;
  62203. }(BABYLON.PostProcess));
  62204. BABYLON.RefractionPostProcess = RefractionPostProcess;
  62205. })(BABYLON || (BABYLON = {}));
  62206. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  62207. var BABYLON;
  62208. (function (BABYLON) {
  62209. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  62210. __extends(BlackAndWhitePostProcess, _super);
  62211. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  62212. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  62213. _this.degree = 1;
  62214. _this.onApplyObservable.add(function (effect) {
  62215. effect.setFloat("degree", _this.degree);
  62216. });
  62217. return _this;
  62218. }
  62219. return BlackAndWhitePostProcess;
  62220. }(BABYLON.PostProcess));
  62221. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  62222. })(BABYLON || (BABYLON = {}));
  62223. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  62224. var BABYLON;
  62225. (function (BABYLON) {
  62226. var ConvolutionPostProcess = /** @class */ (function (_super) {
  62227. __extends(ConvolutionPostProcess, _super);
  62228. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  62229. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  62230. _this.kernel = kernel;
  62231. _this.onApply = function (effect) {
  62232. effect.setFloat2("screenSize", _this.width, _this.height);
  62233. effect.setArray("kernel", _this.kernel);
  62234. };
  62235. return _this;
  62236. }
  62237. // Statics
  62238. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  62239. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  62240. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  62241. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  62242. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  62243. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  62244. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  62245. return ConvolutionPostProcess;
  62246. }(BABYLON.PostProcess));
  62247. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  62248. })(BABYLON || (BABYLON = {}));
  62249. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  62250. var BABYLON;
  62251. (function (BABYLON) {
  62252. var FilterPostProcess = /** @class */ (function (_super) {
  62253. __extends(FilterPostProcess, _super);
  62254. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  62255. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  62256. _this.kernelMatrix = kernelMatrix;
  62257. _this.onApply = function (effect) {
  62258. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  62259. };
  62260. return _this;
  62261. }
  62262. return FilterPostProcess;
  62263. }(BABYLON.PostProcess));
  62264. BABYLON.FilterPostProcess = FilterPostProcess;
  62265. })(BABYLON || (BABYLON = {}));
  62266. //# sourceMappingURL=babylon.filterPostProcess.js.map
  62267. var BABYLON;
  62268. (function (BABYLON) {
  62269. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  62270. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  62271. __extends(VolumetricLightScatteringPostProcess, _super);
  62272. /**
  62273. * @constructor
  62274. * @param {string} name - The post-process name
  62275. * @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)
  62276. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  62277. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  62278. * @param {number} samples - The post-process quality, default 100
  62279. * @param {number} samplingMode - The post-process filtering mode
  62280. * @param {BABYLON.Engine} engine - The babylon engine
  62281. * @param {boolean} reusable - If the post-process is reusable
  62282. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  62283. */
  62284. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  62285. if (samples === void 0) { samples = 100; }
  62286. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62287. 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;
  62288. _this._screenCoordinates = BABYLON.Vector2.Zero();
  62289. /**
  62290. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  62291. * @type {Vector3}
  62292. */
  62293. _this.customMeshPosition = BABYLON.Vector3.Zero();
  62294. /**
  62295. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  62296. * @type {boolean}
  62297. */
  62298. _this.useCustomMeshPosition = false;
  62299. /**
  62300. * If the post-process should inverse the light scattering direction
  62301. * @type {boolean}
  62302. */
  62303. _this.invert = true;
  62304. /**
  62305. * Array containing the excluded meshes not rendered in the internal pass
  62306. */
  62307. _this.excludedMeshes = new Array();
  62308. /**
  62309. * Controls the overall intensity of the post-process
  62310. * @type {number}
  62311. */
  62312. _this.exposure = 0.3;
  62313. /**
  62314. * Dissipates each sample's contribution in range [0, 1]
  62315. * @type {number}
  62316. */
  62317. _this.decay = 0.96815;
  62318. /**
  62319. * Controls the overall intensity of each sample
  62320. * @type {number}
  62321. */
  62322. _this.weight = 0.58767;
  62323. /**
  62324. * Controls the density of each sample
  62325. * @type {number}
  62326. */
  62327. _this.density = 0.926;
  62328. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  62329. engine = scene.getEngine();
  62330. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  62331. // Configure mesh
  62332. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  62333. // Configure
  62334. _this._createPass(scene, ratio.passRatio || ratio);
  62335. _this.onActivate = function (camera) {
  62336. if (!_this.isSupported) {
  62337. _this.dispose(camera);
  62338. }
  62339. _this.onActivate = null;
  62340. };
  62341. _this.onApplyObservable.add(function (effect) {
  62342. _this._updateMeshScreenCoordinates(scene);
  62343. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  62344. effect.setFloat("exposure", _this.exposure);
  62345. effect.setFloat("decay", _this.decay);
  62346. effect.setFloat("weight", _this.weight);
  62347. effect.setFloat("density", _this.density);
  62348. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  62349. });
  62350. return _this;
  62351. }
  62352. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  62353. get: function () {
  62354. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  62355. return false;
  62356. },
  62357. set: function (useDiffuseColor) {
  62358. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  62359. },
  62360. enumerable: true,
  62361. configurable: true
  62362. });
  62363. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  62364. return "VolumetricLightScatteringPostProcess";
  62365. };
  62366. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  62367. var mesh = subMesh.getMesh();
  62368. // Render this.mesh as default
  62369. if (mesh === this.mesh && mesh.material) {
  62370. return mesh.material.isReady(mesh);
  62371. }
  62372. var defines = [];
  62373. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62374. var material = subMesh.getMaterial();
  62375. // Alpha test
  62376. if (material) {
  62377. if (material.needAlphaTesting()) {
  62378. defines.push("#define ALPHATEST");
  62379. }
  62380. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62381. attribs.push(BABYLON.VertexBuffer.UVKind);
  62382. defines.push("#define UV1");
  62383. }
  62384. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62385. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62386. defines.push("#define UV2");
  62387. }
  62388. }
  62389. // Bones
  62390. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62391. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62392. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62393. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62394. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  62395. }
  62396. else {
  62397. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62398. }
  62399. // Instances
  62400. if (useInstances) {
  62401. defines.push("#define INSTANCES");
  62402. attribs.push("world0");
  62403. attribs.push("world1");
  62404. attribs.push("world2");
  62405. attribs.push("world3");
  62406. }
  62407. // Get correct effect
  62408. var join = defines.join("\n");
  62409. if (this._cachedDefines !== join) {
  62410. this._cachedDefines = join;
  62411. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  62412. }
  62413. return this._volumetricLightScatteringPass.isReady();
  62414. };
  62415. /**
  62416. * Sets the new light position for light scattering effect
  62417. * @param {BABYLON.Vector3} The new custom light position
  62418. */
  62419. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  62420. this.customMeshPosition = position;
  62421. };
  62422. /**
  62423. * Returns the light position for light scattering effect
  62424. * @return {BABYLON.Vector3} The custom light position
  62425. */
  62426. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  62427. return this.customMeshPosition;
  62428. };
  62429. /**
  62430. * Disposes the internal assets and detaches the post-process from the camera
  62431. */
  62432. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  62433. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  62434. if (rttIndex !== -1) {
  62435. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  62436. }
  62437. this._volumetricLightScatteringRTT.dispose();
  62438. _super.prototype.dispose.call(this, camera);
  62439. };
  62440. /**
  62441. * Returns the render target texture used by the post-process
  62442. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  62443. */
  62444. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  62445. return this._volumetricLightScatteringRTT;
  62446. };
  62447. // Private methods
  62448. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  62449. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  62450. return true;
  62451. }
  62452. return false;
  62453. };
  62454. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  62455. var _this = this;
  62456. var engine = scene.getEngine();
  62457. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62458. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62459. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62460. this._volumetricLightScatteringRTT.renderList = null;
  62461. this._volumetricLightScatteringRTT.renderParticles = false;
  62462. var camera = this.getCamera();
  62463. if (camera) {
  62464. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  62465. }
  62466. else {
  62467. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  62468. }
  62469. // Custom render function for submeshes
  62470. var renderSubMesh = function (subMesh) {
  62471. var mesh = subMesh.getRenderingMesh();
  62472. if (_this._meshExcluded(mesh)) {
  62473. return;
  62474. }
  62475. var material = subMesh.getMaterial();
  62476. if (!material) {
  62477. return;
  62478. }
  62479. var scene = mesh.getScene();
  62480. var engine = scene.getEngine();
  62481. // Culling
  62482. engine.setState(material.backFaceCulling);
  62483. // Managing instances
  62484. var batch = mesh._getInstancesRenderList(subMesh._id);
  62485. if (batch.mustReturn) {
  62486. return;
  62487. }
  62488. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  62489. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  62490. var effect = _this._volumetricLightScatteringPass;
  62491. if (mesh === _this.mesh) {
  62492. if (subMesh.effect) {
  62493. effect = subMesh.effect;
  62494. }
  62495. else {
  62496. effect = material.getEffect();
  62497. }
  62498. }
  62499. engine.enableEffect(effect);
  62500. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  62501. if (mesh === _this.mesh) {
  62502. material.bind(mesh.getWorldMatrix(), mesh);
  62503. }
  62504. else {
  62505. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  62506. // Alpha test
  62507. if (material && material.needAlphaTesting()) {
  62508. var alphaTexture = material.getAlphaTestTexture();
  62509. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  62510. if (alphaTexture) {
  62511. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  62512. }
  62513. }
  62514. // Bones
  62515. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62516. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  62517. }
  62518. }
  62519. // Draw
  62520. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  62521. }
  62522. };
  62523. // Render target texture callbacks
  62524. var savedSceneClearColor;
  62525. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  62526. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  62527. savedSceneClearColor = scene.clearColor;
  62528. scene.clearColor = sceneClearColor;
  62529. });
  62530. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  62531. scene.clearColor = savedSceneClearColor;
  62532. });
  62533. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62534. var engine = scene.getEngine();
  62535. var index;
  62536. if (depthOnlySubMeshes.length) {
  62537. engine.setColorWrite(false);
  62538. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62539. renderSubMesh(depthOnlySubMeshes.data[index]);
  62540. }
  62541. engine.setColorWrite(true);
  62542. }
  62543. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62544. renderSubMesh(opaqueSubMeshes.data[index]);
  62545. }
  62546. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62547. renderSubMesh(alphaTestSubMeshes.data[index]);
  62548. }
  62549. if (transparentSubMeshes.length) {
  62550. // Sort sub meshes
  62551. for (index = 0; index < transparentSubMeshes.length; index++) {
  62552. var submesh = transparentSubMeshes.data[index];
  62553. var boundingInfo = submesh.getBoundingInfo();
  62554. if (boundingInfo && scene.activeCamera) {
  62555. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  62556. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  62557. }
  62558. }
  62559. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  62560. sortedArray.sort(function (a, b) {
  62561. // Alpha index first
  62562. if (a._alphaIndex > b._alphaIndex) {
  62563. return 1;
  62564. }
  62565. if (a._alphaIndex < b._alphaIndex) {
  62566. return -1;
  62567. }
  62568. // Then distance to camera
  62569. if (a._distanceToCamera < b._distanceToCamera) {
  62570. return 1;
  62571. }
  62572. if (a._distanceToCamera > b._distanceToCamera) {
  62573. return -1;
  62574. }
  62575. return 0;
  62576. });
  62577. // Render sub meshes
  62578. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62579. for (index = 0; index < sortedArray.length; index++) {
  62580. renderSubMesh(sortedArray[index]);
  62581. }
  62582. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62583. }
  62584. };
  62585. };
  62586. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  62587. var transform = scene.getTransformMatrix();
  62588. var meshPosition;
  62589. if (this.useCustomMeshPosition) {
  62590. meshPosition = this.customMeshPosition;
  62591. }
  62592. else if (this.attachedNode) {
  62593. meshPosition = this.attachedNode.position;
  62594. }
  62595. else {
  62596. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  62597. }
  62598. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  62599. this._screenCoordinates.x = pos.x / this._viewPort.width;
  62600. this._screenCoordinates.y = pos.y / this._viewPort.height;
  62601. if (this.invert)
  62602. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  62603. };
  62604. // Static methods
  62605. /**
  62606. * Creates a default mesh for the Volumeric Light Scattering post-process
  62607. * @param {string} The mesh name
  62608. * @param {BABYLON.Scene} The scene where to create the mesh
  62609. * @return {BABYLON.Mesh} the default mesh
  62610. */
  62611. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  62612. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  62613. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  62614. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  62615. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  62616. mesh.material = material;
  62617. return mesh;
  62618. };
  62619. __decorate([
  62620. BABYLON.serializeAsVector3()
  62621. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  62622. __decorate([
  62623. BABYLON.serialize()
  62624. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  62625. __decorate([
  62626. BABYLON.serialize()
  62627. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  62628. __decorate([
  62629. BABYLON.serializeAsMeshReference()
  62630. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  62631. __decorate([
  62632. BABYLON.serialize()
  62633. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  62634. __decorate([
  62635. BABYLON.serialize()
  62636. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  62637. __decorate([
  62638. BABYLON.serialize()
  62639. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  62640. __decorate([
  62641. BABYLON.serialize()
  62642. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  62643. __decorate([
  62644. BABYLON.serialize()
  62645. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  62646. return VolumetricLightScatteringPostProcess;
  62647. }(BABYLON.PostProcess));
  62648. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  62649. })(BABYLON || (BABYLON = {}));
  62650. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  62651. //
  62652. // This post-process allows the modification of rendered colors by using
  62653. // a 'look-up table' (LUT). This effect is also called Color Grading.
  62654. //
  62655. // The object needs to be provided an url to a texture containing the color
  62656. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  62657. // Use an image editing software to tweak the LUT to match your needs.
  62658. //
  62659. // For an example of a color LUT, see here:
  62660. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  62661. // For explanations on color grading, see here:
  62662. // http://udn.epicgames.com/Three/ColorGrading.html
  62663. //
  62664. var BABYLON;
  62665. (function (BABYLON) {
  62666. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  62667. __extends(ColorCorrectionPostProcess, _super);
  62668. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  62669. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  62670. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62671. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  62672. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62673. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62674. _this.onApply = function (effect) {
  62675. effect.setTexture("colorTable", _this._colorTableTexture);
  62676. };
  62677. return _this;
  62678. }
  62679. return ColorCorrectionPostProcess;
  62680. }(BABYLON.PostProcess));
  62681. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  62682. })(BABYLON || (BABYLON = {}));
  62683. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  62684. var BABYLON;
  62685. (function (BABYLON) {
  62686. var TonemappingOperator;
  62687. (function (TonemappingOperator) {
  62688. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  62689. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  62690. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  62691. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  62692. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  62693. ;
  62694. var TonemapPostProcess = /** @class */ (function (_super) {
  62695. __extends(TonemapPostProcess, _super);
  62696. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  62697. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62698. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62699. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  62700. _this._operator = _operator;
  62701. _this.exposureAdjustment = exposureAdjustment;
  62702. var defines = "#define ";
  62703. if (_this._operator === TonemappingOperator.Hable)
  62704. defines += "HABLE_TONEMAPPING";
  62705. else if (_this._operator === TonemappingOperator.Reinhard)
  62706. defines += "REINHARD_TONEMAPPING";
  62707. else if (_this._operator === TonemappingOperator.HejiDawson)
  62708. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  62709. else if (_this._operator === TonemappingOperator.Photographic)
  62710. defines += "PHOTOGRAPHIC_TONEMAPPING";
  62711. //sadly a second call to create the effect.
  62712. _this.updateEffect(defines);
  62713. _this.onApply = function (effect) {
  62714. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  62715. };
  62716. return _this;
  62717. }
  62718. return TonemapPostProcess;
  62719. }(BABYLON.PostProcess));
  62720. BABYLON.TonemapPostProcess = TonemapPostProcess;
  62721. })(BABYLON || (BABYLON = {}));
  62722. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  62723. var BABYLON;
  62724. (function (BABYLON) {
  62725. var DisplayPassPostProcess = /** @class */ (function (_super) {
  62726. __extends(DisplayPassPostProcess, _super);
  62727. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  62728. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  62729. }
  62730. return DisplayPassPostProcess;
  62731. }(BABYLON.PostProcess));
  62732. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  62733. })(BABYLON || (BABYLON = {}));
  62734. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  62735. var BABYLON;
  62736. (function (BABYLON) {
  62737. var HighlightsPostProcess = /** @class */ (function (_super) {
  62738. __extends(HighlightsPostProcess, _super);
  62739. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  62740. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62741. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  62742. }
  62743. return HighlightsPostProcess;
  62744. }(BABYLON.PostProcess));
  62745. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  62746. })(BABYLON || (BABYLON = {}));
  62747. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  62748. var BABYLON;
  62749. (function (BABYLON) {
  62750. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  62751. __extends(ImageProcessingPostProcess, _super);
  62752. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  62753. if (camera === void 0) { camera = null; }
  62754. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62755. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  62756. _this._fromLinearSpace = true;
  62757. /**
  62758. * Defines cache preventing GC.
  62759. */
  62760. _this._defines = {
  62761. IMAGEPROCESSING: false,
  62762. VIGNETTE: false,
  62763. VIGNETTEBLENDMODEMULTIPLY: false,
  62764. VIGNETTEBLENDMODEOPAQUE: false,
  62765. TONEMAPPING: false,
  62766. CONTRAST: false,
  62767. COLORCURVES: false,
  62768. COLORGRADING: false,
  62769. COLORGRADING3D: false,
  62770. FROMLINEARSPACE: false,
  62771. SAMPLER3DGREENDEPTH: false,
  62772. SAMPLER3DBGRMAP: false,
  62773. IMAGEPROCESSINGPOSTPROCESS: false,
  62774. EXPOSURE: false,
  62775. };
  62776. // Setup the configuration as forced by the constructor. This would then not force the
  62777. // scene materials output in linear space and let untouched the default forward pass.
  62778. if (imageProcessingConfiguration) {
  62779. imageProcessingConfiguration.applyByPostProcess = true;
  62780. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  62781. // This will cause the shader to be compiled
  62782. _this.fromLinearSpace = false;
  62783. }
  62784. else {
  62785. _this._attachImageProcessingConfiguration(null, true);
  62786. _this.imageProcessingConfiguration.applyByPostProcess = true;
  62787. }
  62788. _this.onApply = function (effect) {
  62789. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  62790. };
  62791. return _this;
  62792. }
  62793. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  62794. /**
  62795. * Gets the image processing configuration used either in this material.
  62796. */
  62797. get: function () {
  62798. return this._imageProcessingConfiguration;
  62799. },
  62800. /**
  62801. * Sets the Default image processing configuration used either in the this material.
  62802. *
  62803. * If sets to null, the scene one is in use.
  62804. */
  62805. set: function (value) {
  62806. this._attachImageProcessingConfiguration(value);
  62807. },
  62808. enumerable: true,
  62809. configurable: true
  62810. });
  62811. /**
  62812. * Attaches a new image processing configuration to the PBR Material.
  62813. * @param configuration
  62814. */
  62815. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  62816. var _this = this;
  62817. if (doNotBuild === void 0) { doNotBuild = false; }
  62818. if (configuration === this._imageProcessingConfiguration) {
  62819. return;
  62820. }
  62821. // Detaches observer.
  62822. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  62823. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  62824. }
  62825. // Pick the scene configuration if needed.
  62826. if (!configuration) {
  62827. var scene = null;
  62828. var engine = this.getEngine();
  62829. var camera = this.getCamera();
  62830. if (camera) {
  62831. scene = camera.getScene();
  62832. }
  62833. else if (engine && engine.scenes) {
  62834. var scenes = engine.scenes;
  62835. scene = scenes[scenes.length - 1];
  62836. }
  62837. else {
  62838. scene = BABYLON.Engine.LastCreatedScene;
  62839. }
  62840. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  62841. }
  62842. else {
  62843. this._imageProcessingConfiguration = configuration;
  62844. }
  62845. // Attaches observer.
  62846. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  62847. _this._updateParameters();
  62848. });
  62849. // Ensure the effect will be rebuilt.
  62850. if (!doNotBuild) {
  62851. this._updateParameters();
  62852. }
  62853. };
  62854. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  62855. /**
  62856. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  62857. */
  62858. get: function () {
  62859. return this.imageProcessingConfiguration.colorCurves;
  62860. },
  62861. /**
  62862. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  62863. */
  62864. set: function (value) {
  62865. this.imageProcessingConfiguration.colorCurves = value;
  62866. },
  62867. enumerable: true,
  62868. configurable: true
  62869. });
  62870. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  62871. /**
  62872. * Gets wether the color curves effect is enabled.
  62873. */
  62874. get: function () {
  62875. return this.imageProcessingConfiguration.colorCurvesEnabled;
  62876. },
  62877. /**
  62878. * Sets wether the color curves effect is enabled.
  62879. */
  62880. set: function (value) {
  62881. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  62882. },
  62883. enumerable: true,
  62884. configurable: true
  62885. });
  62886. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  62887. /**
  62888. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62889. */
  62890. get: function () {
  62891. return this.imageProcessingConfiguration.colorGradingTexture;
  62892. },
  62893. /**
  62894. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62895. */
  62896. set: function (value) {
  62897. this.imageProcessingConfiguration.colorGradingTexture = value;
  62898. },
  62899. enumerable: true,
  62900. configurable: true
  62901. });
  62902. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  62903. /**
  62904. * Gets wether the color grading effect is enabled.
  62905. */
  62906. get: function () {
  62907. return this.imageProcessingConfiguration.colorGradingEnabled;
  62908. },
  62909. /**
  62910. * Gets wether the color grading effect is enabled.
  62911. */
  62912. set: function (value) {
  62913. this.imageProcessingConfiguration.colorGradingEnabled = value;
  62914. },
  62915. enumerable: true,
  62916. configurable: true
  62917. });
  62918. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  62919. /**
  62920. * Gets exposure used in the effect.
  62921. */
  62922. get: function () {
  62923. return this.imageProcessingConfiguration.exposure;
  62924. },
  62925. /**
  62926. * Sets exposure used in the effect.
  62927. */
  62928. set: function (value) {
  62929. this.imageProcessingConfiguration.exposure = value;
  62930. },
  62931. enumerable: true,
  62932. configurable: true
  62933. });
  62934. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  62935. /**
  62936. * Gets wether tonemapping is enabled or not.
  62937. */
  62938. get: function () {
  62939. return this._imageProcessingConfiguration.toneMappingEnabled;
  62940. },
  62941. /**
  62942. * Sets wether tonemapping is enabled or not
  62943. */
  62944. set: function (value) {
  62945. this._imageProcessingConfiguration.toneMappingEnabled = value;
  62946. },
  62947. enumerable: true,
  62948. configurable: true
  62949. });
  62950. ;
  62951. ;
  62952. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  62953. /**
  62954. * Gets contrast used in the effect.
  62955. */
  62956. get: function () {
  62957. return this.imageProcessingConfiguration.contrast;
  62958. },
  62959. /**
  62960. * Sets contrast used in the effect.
  62961. */
  62962. set: function (value) {
  62963. this.imageProcessingConfiguration.contrast = value;
  62964. },
  62965. enumerable: true,
  62966. configurable: true
  62967. });
  62968. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  62969. /**
  62970. * Gets Vignette stretch size.
  62971. */
  62972. get: function () {
  62973. return this.imageProcessingConfiguration.vignetteStretch;
  62974. },
  62975. /**
  62976. * Sets Vignette stretch size.
  62977. */
  62978. set: function (value) {
  62979. this.imageProcessingConfiguration.vignetteStretch = value;
  62980. },
  62981. enumerable: true,
  62982. configurable: true
  62983. });
  62984. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  62985. /**
  62986. * Gets Vignette centre X Offset.
  62987. */
  62988. get: function () {
  62989. return this.imageProcessingConfiguration.vignetteCentreX;
  62990. },
  62991. /**
  62992. * Sets Vignette centre X Offset.
  62993. */
  62994. set: function (value) {
  62995. this.imageProcessingConfiguration.vignetteCentreX = value;
  62996. },
  62997. enumerable: true,
  62998. configurable: true
  62999. });
  63000. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  63001. /**
  63002. * Gets Vignette centre Y Offset.
  63003. */
  63004. get: function () {
  63005. return this.imageProcessingConfiguration.vignetteCentreY;
  63006. },
  63007. /**
  63008. * Sets Vignette centre Y Offset.
  63009. */
  63010. set: function (value) {
  63011. this.imageProcessingConfiguration.vignetteCentreY = value;
  63012. },
  63013. enumerable: true,
  63014. configurable: true
  63015. });
  63016. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  63017. /**
  63018. * Gets Vignette weight or intensity of the vignette effect.
  63019. */
  63020. get: function () {
  63021. return this.imageProcessingConfiguration.vignetteWeight;
  63022. },
  63023. /**
  63024. * Sets Vignette weight or intensity of the vignette effect.
  63025. */
  63026. set: function (value) {
  63027. this.imageProcessingConfiguration.vignetteWeight = value;
  63028. },
  63029. enumerable: true,
  63030. configurable: true
  63031. });
  63032. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  63033. /**
  63034. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  63035. * if vignetteEnabled is set to true.
  63036. */
  63037. get: function () {
  63038. return this.imageProcessingConfiguration.vignetteColor;
  63039. },
  63040. /**
  63041. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  63042. * if vignetteEnabled is set to true.
  63043. */
  63044. set: function (value) {
  63045. this.imageProcessingConfiguration.vignetteColor = value;
  63046. },
  63047. enumerable: true,
  63048. configurable: true
  63049. });
  63050. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  63051. /**
  63052. * Gets Camera field of view used by the Vignette effect.
  63053. */
  63054. get: function () {
  63055. return this.imageProcessingConfiguration.vignetteCameraFov;
  63056. },
  63057. /**
  63058. * Sets Camera field of view used by the Vignette effect.
  63059. */
  63060. set: function (value) {
  63061. this.imageProcessingConfiguration.vignetteCameraFov = value;
  63062. },
  63063. enumerable: true,
  63064. configurable: true
  63065. });
  63066. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  63067. /**
  63068. * Gets the vignette blend mode allowing different kind of effect.
  63069. */
  63070. get: function () {
  63071. return this.imageProcessingConfiguration.vignetteBlendMode;
  63072. },
  63073. /**
  63074. * Sets the vignette blend mode allowing different kind of effect.
  63075. */
  63076. set: function (value) {
  63077. this.imageProcessingConfiguration.vignetteBlendMode = value;
  63078. },
  63079. enumerable: true,
  63080. configurable: true
  63081. });
  63082. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  63083. /**
  63084. * Gets wether the vignette effect is enabled.
  63085. */
  63086. get: function () {
  63087. return this.imageProcessingConfiguration.vignetteEnabled;
  63088. },
  63089. /**
  63090. * Sets wether the vignette effect is enabled.
  63091. */
  63092. set: function (value) {
  63093. this.imageProcessingConfiguration.vignetteEnabled = value;
  63094. },
  63095. enumerable: true,
  63096. configurable: true
  63097. });
  63098. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  63099. /**
  63100. * Gets wether the input of the processing is in Gamma or Linear Space.
  63101. */
  63102. get: function () {
  63103. return this._fromLinearSpace;
  63104. },
  63105. /**
  63106. * Sets wether the input of the processing is in Gamma or Linear Space.
  63107. */
  63108. set: function (value) {
  63109. if (this._fromLinearSpace === value) {
  63110. return;
  63111. }
  63112. this._fromLinearSpace = value;
  63113. this._updateParameters();
  63114. },
  63115. enumerable: true,
  63116. configurable: true
  63117. });
  63118. ImageProcessingPostProcess.prototype.getClassName = function () {
  63119. return "ImageProcessingPostProcess";
  63120. };
  63121. ImageProcessingPostProcess.prototype._updateParameters = function () {
  63122. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  63123. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  63124. var defines = "";
  63125. for (var define in this._defines) {
  63126. if (this._defines[define]) {
  63127. defines += "#define " + define + ";\r\n";
  63128. }
  63129. }
  63130. var samplers = ["textureSampler"];
  63131. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  63132. var uniforms = ["scale"];
  63133. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  63134. this.updateEffect(defines, uniforms, samplers);
  63135. };
  63136. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  63137. _super.prototype.dispose.call(this, camera);
  63138. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  63139. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  63140. }
  63141. this.imageProcessingConfiguration.applyByPostProcess = false;
  63142. };
  63143. __decorate([
  63144. BABYLON.serialize()
  63145. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  63146. return ImageProcessingPostProcess;
  63147. }(BABYLON.PostProcess));
  63148. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  63149. })(BABYLON || (BABYLON = {}));
  63150. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  63151. var BABYLON;
  63152. (function (BABYLON) {
  63153. var BlurPostProcess = /** @class */ (function (_super) {
  63154. __extends(BlurPostProcess, _super);
  63155. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  63156. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63157. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63158. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  63159. _this.direction = direction;
  63160. _this._packedFloat = false;
  63161. _this.onApplyObservable.add(function (effect) {
  63162. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  63163. });
  63164. _this.kernel = kernel;
  63165. return _this;
  63166. }
  63167. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  63168. /**
  63169. * Gets the length in pixels of the blur sample region
  63170. */
  63171. get: function () {
  63172. return this._idealKernel;
  63173. },
  63174. /**
  63175. * Sets the length in pixels of the blur sample region
  63176. */
  63177. set: function (v) {
  63178. if (this._idealKernel === v) {
  63179. return;
  63180. }
  63181. v = Math.max(v, 1);
  63182. this._idealKernel = v;
  63183. this._kernel = this._nearestBestKernel(v);
  63184. this._updateParameters();
  63185. },
  63186. enumerable: true,
  63187. configurable: true
  63188. });
  63189. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  63190. /**
  63191. * Gets wether or not the blur is unpacking/repacking floats
  63192. */
  63193. get: function () {
  63194. return this._packedFloat;
  63195. },
  63196. /**
  63197. * Sets wether or not the blur needs to unpack/repack floats
  63198. */
  63199. set: function (v) {
  63200. if (this._packedFloat === v) {
  63201. return;
  63202. }
  63203. this._packedFloat = v;
  63204. this._updateParameters();
  63205. },
  63206. enumerable: true,
  63207. configurable: true
  63208. });
  63209. BlurPostProcess.prototype._updateParameters = function () {
  63210. // Generate sampling offsets and weights
  63211. var N = this._kernel;
  63212. var centerIndex = (N - 1) / 2;
  63213. // Generate Gaussian sampling weights over kernel
  63214. var offsets = [];
  63215. var weights = [];
  63216. var totalWeight = 0;
  63217. for (var i = 0; i < N; i++) {
  63218. var u = i / (N - 1);
  63219. var w = this._gaussianWeight(u * 2.0 - 1);
  63220. offsets[i] = (i - centerIndex);
  63221. weights[i] = w;
  63222. totalWeight += w;
  63223. }
  63224. // Normalize weights
  63225. for (var i = 0; i < weights.length; i++) {
  63226. weights[i] /= totalWeight;
  63227. }
  63228. // Optimize: combine samples to take advantage of hardware linear sampling
  63229. // Walk from left to center, combining pairs (symmetrically)
  63230. var linearSamplingWeights = [];
  63231. var linearSamplingOffsets = [];
  63232. var linearSamplingMap = [];
  63233. for (var i = 0; i <= centerIndex; i += 2) {
  63234. var j = Math.min(i + 1, Math.floor(centerIndex));
  63235. var singleCenterSample = i === j;
  63236. if (singleCenterSample) {
  63237. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  63238. }
  63239. else {
  63240. var sharedCell = j === centerIndex;
  63241. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  63242. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  63243. if (offsetLinear === 0) {
  63244. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  63245. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  63246. }
  63247. else {
  63248. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  63249. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  63250. }
  63251. }
  63252. }
  63253. for (var i = 0; i < linearSamplingMap.length; i++) {
  63254. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  63255. linearSamplingWeights[i] = linearSamplingMap[i].w;
  63256. }
  63257. // Replace with optimized
  63258. offsets = linearSamplingOffsets;
  63259. weights = linearSamplingWeights;
  63260. // Generate shaders
  63261. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  63262. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  63263. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  63264. var defines = "";
  63265. for (var i = 0; i < varyingCount; i++) {
  63266. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  63267. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  63268. }
  63269. var depCount = 0;
  63270. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  63271. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  63272. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  63273. depCount++;
  63274. }
  63275. if (this.packedFloat) {
  63276. defines += "#define PACKEDFLOAT 1";
  63277. }
  63278. this.updateEffect(defines, null, null, {
  63279. varyingCount: varyingCount,
  63280. depCount: depCount
  63281. });
  63282. };
  63283. /**
  63284. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  63285. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  63286. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  63287. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  63288. * The gaps between physical kernels are compensated for in the weighting of the samples
  63289. * @param idealKernel Ideal blur kernel.
  63290. * @return Nearest best kernel.
  63291. */
  63292. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  63293. var v = Math.round(idealKernel);
  63294. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  63295. var k = _a[_i];
  63296. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  63297. return Math.max(k, 3);
  63298. }
  63299. }
  63300. return Math.max(v, 3);
  63301. };
  63302. /**
  63303. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  63304. * @param x The point on the Gaussian distribution to sample.
  63305. * @return the value of the Gaussian function at x.
  63306. */
  63307. BlurPostProcess.prototype._gaussianWeight = function (x) {
  63308. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  63309. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  63310. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  63311. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  63312. // truncated at around 1.3% of peak strength.
  63313. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  63314. var sigma = (1 / 3);
  63315. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  63316. var exponent = -((x * x) / (2.0 * sigma * sigma));
  63317. var weight = (1.0 / denominator) * Math.exp(exponent);
  63318. return weight;
  63319. };
  63320. /**
  63321. * Generates a string that can be used as a floating point number in GLSL.
  63322. * @param x Value to print.
  63323. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  63324. * @return GLSL float string.
  63325. */
  63326. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  63327. if (decimalFigures === void 0) { decimalFigures = 8; }
  63328. return x.toFixed(decimalFigures).replace(/0+$/, '');
  63329. };
  63330. return BlurPostProcess;
  63331. }(BABYLON.PostProcess));
  63332. BABYLON.BlurPostProcess = BlurPostProcess;
  63333. })(BABYLON || (BABYLON = {}));
  63334. //# sourceMappingURL=babylon.blurPostProcess.js.map
  63335. var BABYLON;
  63336. (function (BABYLON) {
  63337. var Bone = /** @class */ (function (_super) {
  63338. __extends(Bone, _super);
  63339. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  63340. if (parentBone === void 0) { parentBone = null; }
  63341. if (localMatrix === void 0) { localMatrix = null; }
  63342. if (restPose === void 0) { restPose = null; }
  63343. if (baseMatrix === void 0) { baseMatrix = null; }
  63344. if (index === void 0) { index = null; }
  63345. var _this = _super.call(this, name, skeleton.getScene()) || this;
  63346. _this.name = name;
  63347. _this.children = new Array();
  63348. _this.animations = new Array();
  63349. // Set this value to map this bone to a different index in the transform matrices.
  63350. // Set this value to -1 to exclude the bone from the transform matrices.
  63351. _this._index = null;
  63352. _this._worldTransform = new BABYLON.Matrix();
  63353. _this._absoluteTransform = new BABYLON.Matrix();
  63354. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  63355. _this._scaleMatrix = BABYLON.Matrix.Identity();
  63356. _this._scaleVector = BABYLON.Vector3.One();
  63357. _this._negateScaleChildren = BABYLON.Vector3.One();
  63358. _this._scalingDeterminant = 1;
  63359. _this._skeleton = skeleton;
  63360. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  63361. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  63362. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  63363. _this._index = index;
  63364. skeleton.bones.push(_this);
  63365. _this.setParent(parentBone, false);
  63366. _this._updateDifferenceMatrix();
  63367. return _this;
  63368. }
  63369. Object.defineProperty(Bone.prototype, "_matrix", {
  63370. get: function () {
  63371. return this._localMatrix;
  63372. },
  63373. set: function (val) {
  63374. if (this._localMatrix) {
  63375. this._localMatrix.copyFrom(val);
  63376. }
  63377. else {
  63378. this._localMatrix = val;
  63379. }
  63380. },
  63381. enumerable: true,
  63382. configurable: true
  63383. });
  63384. // Members
  63385. Bone.prototype.getSkeleton = function () {
  63386. return this._skeleton;
  63387. };
  63388. Bone.prototype.getParent = function () {
  63389. return this._parent;
  63390. };
  63391. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  63392. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  63393. if (this._parent === parent) {
  63394. return;
  63395. }
  63396. if (this._parent) {
  63397. var index = this._parent.children.indexOf(this);
  63398. if (index !== -1) {
  63399. this._parent.children.splice(index, 1);
  63400. }
  63401. }
  63402. this._parent = parent;
  63403. if (this._parent) {
  63404. this._parent.children.push(this);
  63405. }
  63406. if (updateDifferenceMatrix) {
  63407. this._updateDifferenceMatrix();
  63408. }
  63409. };
  63410. Bone.prototype.getLocalMatrix = function () {
  63411. return this._localMatrix;
  63412. };
  63413. Bone.prototype.getBaseMatrix = function () {
  63414. return this._baseMatrix;
  63415. };
  63416. Bone.prototype.getRestPose = function () {
  63417. return this._restPose;
  63418. };
  63419. Bone.prototype.returnToRest = function () {
  63420. this.updateMatrix(this._restPose.clone());
  63421. };
  63422. Bone.prototype.getWorldMatrix = function () {
  63423. return this._worldTransform;
  63424. };
  63425. Bone.prototype.getInvertedAbsoluteTransform = function () {
  63426. return this._invertedAbsoluteTransform;
  63427. };
  63428. Bone.prototype.getAbsoluteTransform = function () {
  63429. return this._absoluteTransform;
  63430. };
  63431. Object.defineProperty(Bone.prototype, "position", {
  63432. // Properties (matches AbstractMesh properties)
  63433. get: function () {
  63434. return this.getPosition();
  63435. },
  63436. set: function (newPosition) {
  63437. this.setPosition(newPosition);
  63438. },
  63439. enumerable: true,
  63440. configurable: true
  63441. });
  63442. Object.defineProperty(Bone.prototype, "rotation", {
  63443. get: function () {
  63444. return this.getRotation();
  63445. },
  63446. set: function (newRotation) {
  63447. this.setRotation(newRotation);
  63448. },
  63449. enumerable: true,
  63450. configurable: true
  63451. });
  63452. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  63453. get: function () {
  63454. return this.getRotationQuaternion();
  63455. },
  63456. set: function (newRotation) {
  63457. this.setRotationQuaternion(newRotation);
  63458. },
  63459. enumerable: true,
  63460. configurable: true
  63461. });
  63462. Object.defineProperty(Bone.prototype, "scaling", {
  63463. get: function () {
  63464. return this.getScale();
  63465. },
  63466. set: function (newScaling) {
  63467. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  63468. },
  63469. enumerable: true,
  63470. configurable: true
  63471. });
  63472. // Methods
  63473. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  63474. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  63475. this._baseMatrix = matrix.clone();
  63476. this._localMatrix = matrix.clone();
  63477. this._skeleton._markAsDirty();
  63478. if (updateDifferenceMatrix) {
  63479. this._updateDifferenceMatrix();
  63480. }
  63481. };
  63482. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  63483. if (!rootMatrix) {
  63484. rootMatrix = this._baseMatrix;
  63485. }
  63486. if (this._parent) {
  63487. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  63488. }
  63489. else {
  63490. this._absoluteTransform.copyFrom(rootMatrix);
  63491. }
  63492. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  63493. for (var index = 0; index < this.children.length; index++) {
  63494. this.children[index]._updateDifferenceMatrix();
  63495. }
  63496. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  63497. };
  63498. Bone.prototype.markAsDirty = function () {
  63499. this._currentRenderId++;
  63500. this._skeleton._markAsDirty();
  63501. };
  63502. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  63503. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  63504. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  63505. // all animation may be coming from a library skeleton, so may need to create animation
  63506. if (this.animations.length === 0) {
  63507. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  63508. this.animations[0].setKeys([]);
  63509. }
  63510. // get animation info / verify there is such a range from the source bone
  63511. var sourceRange = source.animations[0].getRange(rangeName);
  63512. if (!sourceRange) {
  63513. return false;
  63514. }
  63515. var from = sourceRange.from;
  63516. var to = sourceRange.to;
  63517. var sourceKeys = source.animations[0].getKeys();
  63518. // rescaling prep
  63519. var sourceBoneLength = source.length;
  63520. var sourceParent = source.getParent();
  63521. var parent = this.getParent();
  63522. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  63523. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  63524. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  63525. var destKeys = this.animations[0].getKeys();
  63526. // loop vars declaration
  63527. var orig;
  63528. var origTranslation;
  63529. var mat;
  63530. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  63531. orig = sourceKeys[key];
  63532. if (orig.frame >= from && orig.frame <= to) {
  63533. if (rescaleAsRequired) {
  63534. mat = orig.value.clone();
  63535. // scale based on parent ratio, when bone has parent
  63536. if (parentScalingReqd) {
  63537. origTranslation = mat.getTranslation();
  63538. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  63539. // scale based on skeleton dimension ratio when root bone, and value is passed
  63540. }
  63541. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  63542. origTranslation = mat.getTranslation();
  63543. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  63544. // use original when root bone, and no data for skelDimensionsRatio
  63545. }
  63546. else {
  63547. mat = orig.value;
  63548. }
  63549. }
  63550. else {
  63551. mat = orig.value;
  63552. }
  63553. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  63554. }
  63555. }
  63556. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  63557. return true;
  63558. };
  63559. /**
  63560. * Translate the bone in local or world space.
  63561. * @param vec The amount to translate the bone.
  63562. * @param space The space that the translation is in.
  63563. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63564. */
  63565. Bone.prototype.translate = function (vec, space, mesh) {
  63566. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63567. var lm = this.getLocalMatrix();
  63568. if (space == BABYLON.Space.LOCAL) {
  63569. lm.m[12] += vec.x;
  63570. lm.m[13] += vec.y;
  63571. lm.m[14] += vec.z;
  63572. }
  63573. else {
  63574. var wm = null;
  63575. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63576. if (mesh) {
  63577. wm = mesh.getWorldMatrix();
  63578. }
  63579. this._skeleton.computeAbsoluteTransforms();
  63580. var tmat = Bone._tmpMats[0];
  63581. var tvec = Bone._tmpVecs[0];
  63582. if (this._parent) {
  63583. if (mesh && wm) {
  63584. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63585. tmat.multiplyToRef(wm, tmat);
  63586. }
  63587. else {
  63588. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63589. }
  63590. }
  63591. tmat.m[12] = 0;
  63592. tmat.m[13] = 0;
  63593. tmat.m[14] = 0;
  63594. tmat.invert();
  63595. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  63596. lm.m[12] += tvec.x;
  63597. lm.m[13] += tvec.y;
  63598. lm.m[14] += tvec.z;
  63599. }
  63600. this.markAsDirty();
  63601. };
  63602. /**
  63603. * Set the postion of the bone in local or world space.
  63604. * @param position The position to set the bone.
  63605. * @param space The space that the position is in.
  63606. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63607. */
  63608. Bone.prototype.setPosition = function (position, space, mesh) {
  63609. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63610. var lm = this.getLocalMatrix();
  63611. if (space == BABYLON.Space.LOCAL) {
  63612. lm.m[12] = position.x;
  63613. lm.m[13] = position.y;
  63614. lm.m[14] = position.z;
  63615. }
  63616. else {
  63617. var wm = null;
  63618. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63619. if (mesh) {
  63620. wm = mesh.getWorldMatrix();
  63621. }
  63622. this._skeleton.computeAbsoluteTransforms();
  63623. var tmat = Bone._tmpMats[0];
  63624. var vec = Bone._tmpVecs[0];
  63625. if (this._parent) {
  63626. if (mesh && wm) {
  63627. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63628. tmat.multiplyToRef(wm, tmat);
  63629. }
  63630. else {
  63631. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63632. }
  63633. }
  63634. tmat.invert();
  63635. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  63636. lm.m[12] = vec.x;
  63637. lm.m[13] = vec.y;
  63638. lm.m[14] = vec.z;
  63639. }
  63640. this.markAsDirty();
  63641. };
  63642. /**
  63643. * Set the absolute postion of the bone (world space).
  63644. * @param position The position to set the bone.
  63645. * @param mesh The mesh that this bone is attached to.
  63646. */
  63647. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  63648. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  63649. };
  63650. /**
  63651. * Set the scale of the bone on the x, y and z axes.
  63652. * @param x The scale of the bone on the x axis.
  63653. * @param x The scale of the bone on the y axis.
  63654. * @param z The scale of the bone on the z axis.
  63655. * @param scaleChildren Set this to true if children of the bone should be scaled.
  63656. */
  63657. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  63658. if (scaleChildren === void 0) { scaleChildren = false; }
  63659. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  63660. if (!scaleChildren) {
  63661. this._negateScaleChildren.x = 1 / x;
  63662. this._negateScaleChildren.y = 1 / y;
  63663. this._negateScaleChildren.z = 1 / z;
  63664. }
  63665. this._syncScaleVector();
  63666. }
  63667. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  63668. };
  63669. /**
  63670. * Scale the bone on the x, y and z axes.
  63671. * @param x The amount to scale the bone on the x axis.
  63672. * @param x The amount to scale the bone on the y axis.
  63673. * @param z The amount to scale the bone on the z axis.
  63674. * @param scaleChildren Set this to true if children of the bone should be scaled.
  63675. */
  63676. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  63677. if (scaleChildren === void 0) { scaleChildren = false; }
  63678. var locMat = this.getLocalMatrix();
  63679. var origLocMat = Bone._tmpMats[0];
  63680. origLocMat.copyFrom(locMat);
  63681. var origLocMatInv = Bone._tmpMats[1];
  63682. origLocMatInv.copyFrom(origLocMat);
  63683. origLocMatInv.invert();
  63684. var scaleMat = Bone._tmpMats[2];
  63685. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  63686. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  63687. this._scaleVector.x *= x;
  63688. this._scaleVector.y *= y;
  63689. this._scaleVector.z *= z;
  63690. locMat.multiplyToRef(origLocMatInv, locMat);
  63691. locMat.multiplyToRef(scaleMat, locMat);
  63692. locMat.multiplyToRef(origLocMat, locMat);
  63693. var parent = this.getParent();
  63694. if (parent) {
  63695. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  63696. }
  63697. else {
  63698. this.getAbsoluteTransform().copyFrom(locMat);
  63699. }
  63700. var len = this.children.length;
  63701. scaleMat.invert();
  63702. for (var i = 0; i < len; i++) {
  63703. var child = this.children[i];
  63704. var cm = child.getLocalMatrix();
  63705. cm.multiplyToRef(scaleMat, cm);
  63706. var lm = child.getLocalMatrix();
  63707. lm.m[12] *= x;
  63708. lm.m[13] *= y;
  63709. lm.m[14] *= z;
  63710. }
  63711. this.computeAbsoluteTransforms();
  63712. if (scaleChildren) {
  63713. for (var i = 0; i < len; i++) {
  63714. this.children[i].scale(x, y, z, scaleChildren);
  63715. }
  63716. }
  63717. this.markAsDirty();
  63718. };
  63719. /**
  63720. * Set the yaw, pitch, and roll of the bone in local or world space.
  63721. * @param yaw The rotation of the bone on the y axis.
  63722. * @param pitch The rotation of the bone on the x axis.
  63723. * @param roll The rotation of the bone on the z axis.
  63724. * @param space The space that the axes of rotation are in.
  63725. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63726. */
  63727. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  63728. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63729. var rotMat = Bone._tmpMats[0];
  63730. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  63731. var rotMatInv = Bone._tmpMats[1];
  63732. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63733. rotMatInv.multiplyToRef(rotMat, rotMat);
  63734. this._rotateWithMatrix(rotMat, space, mesh);
  63735. };
  63736. /**
  63737. * Rotate the bone on an axis in local or world space.
  63738. * @param axis The axis to rotate the bone on.
  63739. * @param amount The amount to rotate the bone.
  63740. * @param space The space that the axis is in.
  63741. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63742. */
  63743. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  63744. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63745. var rmat = Bone._tmpMats[0];
  63746. rmat.m[12] = 0;
  63747. rmat.m[13] = 0;
  63748. rmat.m[14] = 0;
  63749. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  63750. this._rotateWithMatrix(rmat, space, mesh);
  63751. };
  63752. /**
  63753. * Set the rotation of the bone to a particular axis angle in local or world space.
  63754. * @param axis The axis to rotate the bone on.
  63755. * @param angle The angle that the bone should be rotated to.
  63756. * @param space The space that the axis is in.
  63757. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63758. */
  63759. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  63760. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63761. var rotMat = Bone._tmpMats[0];
  63762. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  63763. var rotMatInv = Bone._tmpMats[1];
  63764. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63765. rotMatInv.multiplyToRef(rotMat, rotMat);
  63766. this._rotateWithMatrix(rotMat, space, mesh);
  63767. };
  63768. /**
  63769. * Set the euler rotation of the bone in local of world space.
  63770. * @param rotation The euler rotation that the bone should be set to.
  63771. * @param space The space that the rotation is in.
  63772. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63773. */
  63774. Bone.prototype.setRotation = function (rotation, space, mesh) {
  63775. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63776. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  63777. };
  63778. /**
  63779. * Set the quaternion rotation of the bone in local of world space.
  63780. * @param quat The quaternion rotation that the bone should be set to.
  63781. * @param space The space that the rotation is in.
  63782. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63783. */
  63784. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  63785. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63786. var rotMatInv = Bone._tmpMats[0];
  63787. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63788. var rotMat = Bone._tmpMats[1];
  63789. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  63790. rotMatInv.multiplyToRef(rotMat, rotMat);
  63791. this._rotateWithMatrix(rotMat, space, mesh);
  63792. };
  63793. /**
  63794. * Set the rotation matrix of the bone in local of world space.
  63795. * @param rotMat The rotation matrix that the bone should be set to.
  63796. * @param space The space that the rotation is in.
  63797. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63798. */
  63799. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  63800. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63801. var rotMatInv = Bone._tmpMats[0];
  63802. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63803. var rotMat2 = Bone._tmpMats[1];
  63804. rotMat2.copyFrom(rotMat);
  63805. rotMatInv.multiplyToRef(rotMat, rotMat2);
  63806. this._rotateWithMatrix(rotMat2, space, mesh);
  63807. };
  63808. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  63809. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63810. var lmat = this.getLocalMatrix();
  63811. var lx = lmat.m[12];
  63812. var ly = lmat.m[13];
  63813. var lz = lmat.m[14];
  63814. var parent = this.getParent();
  63815. var parentScale = Bone._tmpMats[3];
  63816. var parentScaleInv = Bone._tmpMats[4];
  63817. if (parent) {
  63818. if (space == BABYLON.Space.WORLD) {
  63819. if (mesh) {
  63820. parentScale.copyFrom(mesh.getWorldMatrix());
  63821. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  63822. }
  63823. else {
  63824. parentScale.copyFrom(parent.getAbsoluteTransform());
  63825. }
  63826. }
  63827. else {
  63828. parentScale = parent._scaleMatrix;
  63829. }
  63830. parentScaleInv.copyFrom(parentScale);
  63831. parentScaleInv.invert();
  63832. lmat.multiplyToRef(parentScale, lmat);
  63833. lmat.multiplyToRef(rmat, lmat);
  63834. lmat.multiplyToRef(parentScaleInv, lmat);
  63835. }
  63836. else {
  63837. if (space == BABYLON.Space.WORLD && mesh) {
  63838. parentScale.copyFrom(mesh.getWorldMatrix());
  63839. parentScaleInv.copyFrom(parentScale);
  63840. parentScaleInv.invert();
  63841. lmat.multiplyToRef(parentScale, lmat);
  63842. lmat.multiplyToRef(rmat, lmat);
  63843. lmat.multiplyToRef(parentScaleInv, lmat);
  63844. }
  63845. else {
  63846. lmat.multiplyToRef(rmat, lmat);
  63847. }
  63848. }
  63849. lmat.m[12] = lx;
  63850. lmat.m[13] = ly;
  63851. lmat.m[14] = lz;
  63852. this.computeAbsoluteTransforms();
  63853. this.markAsDirty();
  63854. };
  63855. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  63856. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63857. if (space == BABYLON.Space.WORLD) {
  63858. var scaleMatrix = Bone._tmpMats[2];
  63859. scaleMatrix.copyFrom(this._scaleMatrix);
  63860. rotMatInv.copyFrom(this.getAbsoluteTransform());
  63861. if (mesh) {
  63862. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  63863. var meshScale = Bone._tmpMats[3];
  63864. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  63865. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  63866. }
  63867. rotMatInv.invert();
  63868. scaleMatrix.m[0] *= this._scalingDeterminant;
  63869. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63870. }
  63871. else {
  63872. rotMatInv.copyFrom(this.getLocalMatrix());
  63873. rotMatInv.invert();
  63874. var scaleMatrix = Bone._tmpMats[2];
  63875. scaleMatrix.copyFrom(this._scaleMatrix);
  63876. if (this._parent) {
  63877. var pscaleMatrix = Bone._tmpMats[3];
  63878. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  63879. pscaleMatrix.invert();
  63880. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  63881. }
  63882. else {
  63883. scaleMatrix.m[0] *= this._scalingDeterminant;
  63884. }
  63885. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63886. }
  63887. };
  63888. /**
  63889. * Get the scale of the bone
  63890. * @returns the scale of the bone
  63891. */
  63892. Bone.prototype.getScale = function () {
  63893. return this._scaleVector.clone();
  63894. };
  63895. /**
  63896. * Copy the scale of the bone to a vector3.
  63897. * @param result The vector3 to copy the scale to
  63898. */
  63899. Bone.prototype.getScaleToRef = function (result) {
  63900. result.copyFrom(this._scaleVector);
  63901. };
  63902. /**
  63903. * Get the position of the bone in local or world space.
  63904. * @param space The space that the returned position is in.
  63905. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63906. * @returns The position of the bone
  63907. */
  63908. Bone.prototype.getPosition = function (space, mesh) {
  63909. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63910. if (mesh === void 0) { mesh = null; }
  63911. var pos = BABYLON.Vector3.Zero();
  63912. this.getPositionToRef(space, mesh, pos);
  63913. return pos;
  63914. };
  63915. /**
  63916. * Copy the position of the bone to a vector3 in local or world space.
  63917. * @param space The space that the returned position is in.
  63918. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63919. * @param result The vector3 to copy the position to.
  63920. */
  63921. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  63922. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63923. if (space == BABYLON.Space.LOCAL) {
  63924. var lm = this.getLocalMatrix();
  63925. result.x = lm.m[12];
  63926. result.y = lm.m[13];
  63927. result.z = lm.m[14];
  63928. }
  63929. else {
  63930. var wm = null;
  63931. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63932. if (mesh) {
  63933. wm = mesh.getWorldMatrix();
  63934. }
  63935. this._skeleton.computeAbsoluteTransforms();
  63936. var tmat = Bone._tmpMats[0];
  63937. if (mesh && wm) {
  63938. tmat.copyFrom(this.getAbsoluteTransform());
  63939. tmat.multiplyToRef(wm, tmat);
  63940. }
  63941. else {
  63942. tmat = this.getAbsoluteTransform();
  63943. }
  63944. result.x = tmat.m[12];
  63945. result.y = tmat.m[13];
  63946. result.z = tmat.m[14];
  63947. }
  63948. };
  63949. /**
  63950. * Get the absolute position of the bone (world space).
  63951. * @param mesh The mesh that this bone is attached to.
  63952. * @returns The absolute position of the bone
  63953. */
  63954. Bone.prototype.getAbsolutePosition = function (mesh) {
  63955. if (mesh === void 0) { mesh = null; }
  63956. var pos = BABYLON.Vector3.Zero();
  63957. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  63958. return pos;
  63959. };
  63960. /**
  63961. * Copy the absolute position of the bone (world space) to the result param.
  63962. * @param mesh The mesh that this bone is attached to.
  63963. * @param result The vector3 to copy the absolute position to.
  63964. */
  63965. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  63966. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  63967. };
  63968. /**
  63969. * Compute the absolute transforms of this bone and its children.
  63970. */
  63971. Bone.prototype.computeAbsoluteTransforms = function () {
  63972. if (this._parent) {
  63973. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  63974. }
  63975. else {
  63976. this._absoluteTransform.copyFrom(this._localMatrix);
  63977. var poseMatrix = this._skeleton.getPoseMatrix();
  63978. if (poseMatrix) {
  63979. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  63980. }
  63981. }
  63982. var children = this.children;
  63983. var len = children.length;
  63984. for (var i = 0; i < len; i++) {
  63985. children[i].computeAbsoluteTransforms();
  63986. }
  63987. };
  63988. Bone.prototype._syncScaleVector = function () {
  63989. var lm = this.getLocalMatrix();
  63990. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  63991. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  63992. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  63993. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  63994. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  63995. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  63996. this._scaleVector.x = xs * Math.sqrt(xsq);
  63997. this._scaleVector.y = ys * Math.sqrt(ysq);
  63998. this._scaleVector.z = zs * Math.sqrt(zsq);
  63999. if (this._parent) {
  64000. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  64001. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  64002. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  64003. }
  64004. 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);
  64005. };
  64006. /**
  64007. * Get the world direction from an axis that is in the local space of the bone.
  64008. * @param localAxis The local direction that is used to compute the world direction.
  64009. * @param mesh The mesh that this bone is attached to.
  64010. * @returns The world direction
  64011. */
  64012. Bone.prototype.getDirection = function (localAxis, mesh) {
  64013. if (mesh === void 0) { mesh = null; }
  64014. var result = BABYLON.Vector3.Zero();
  64015. this.getDirectionToRef(localAxis, mesh, result);
  64016. return result;
  64017. };
  64018. /**
  64019. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  64020. * @param localAxis The local direction that is used to compute the world direction.
  64021. * @param mesh The mesh that this bone is attached to.
  64022. * @param result The vector3 that the world direction will be copied to.
  64023. */
  64024. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  64025. if (mesh === void 0) { mesh = null; }
  64026. var wm = null;
  64027. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  64028. if (mesh) {
  64029. wm = mesh.getWorldMatrix();
  64030. }
  64031. this._skeleton.computeAbsoluteTransforms();
  64032. var mat = Bone._tmpMats[0];
  64033. mat.copyFrom(this.getAbsoluteTransform());
  64034. if (mesh && wm) {
  64035. mat.multiplyToRef(wm, mat);
  64036. }
  64037. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  64038. result.normalize();
  64039. };
  64040. /**
  64041. * Get the euler rotation of the bone in local or world space.
  64042. * @param space The space that the rotation should be in.
  64043. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  64044. * @returns The euler rotation
  64045. */
  64046. Bone.prototype.getRotation = function (space, mesh) {
  64047. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  64048. if (mesh === void 0) { mesh = null; }
  64049. var result = BABYLON.Vector3.Zero();
  64050. this.getRotationToRef(space, mesh, result);
  64051. return result;
  64052. };
  64053. /**
  64054. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  64055. * @param space The space that the rotation should be in.
  64056. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  64057. * @param result The vector3 that the rotation should be copied to.
  64058. */
  64059. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  64060. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  64061. if (mesh === void 0) { mesh = null; }
  64062. var quat = Bone._tmpQuat;
  64063. this.getRotationQuaternionToRef(space, mesh, quat);
  64064. quat.toEulerAnglesToRef(result);
  64065. };
  64066. /**
  64067. * Get the quaternion rotation of the bone in either local or world space.
  64068. * @param space The space that the rotation should be in.
  64069. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  64070. * @returns The quaternion rotation
  64071. */
  64072. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  64073. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  64074. if (mesh === void 0) { mesh = null; }
  64075. var result = BABYLON.Quaternion.Identity();
  64076. this.getRotationQuaternionToRef(space, mesh, result);
  64077. return result;
  64078. };
  64079. /**
  64080. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  64081. * @param space The space that the rotation should be in.
  64082. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  64083. * @param result The quaternion that the rotation should be copied to.
  64084. */
  64085. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  64086. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  64087. if (mesh === void 0) { mesh = null; }
  64088. if (space == BABYLON.Space.LOCAL) {
  64089. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  64090. }
  64091. else {
  64092. var mat = Bone._tmpMats[0];
  64093. var amat = this.getAbsoluteTransform();
  64094. if (mesh) {
  64095. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  64096. }
  64097. else {
  64098. mat.copyFrom(amat);
  64099. }
  64100. mat.m[0] *= this._scalingDeterminant;
  64101. mat.m[1] *= this._scalingDeterminant;
  64102. mat.m[2] *= this._scalingDeterminant;
  64103. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  64104. }
  64105. };
  64106. /**
  64107. * Get the rotation matrix of the bone in local or world space.
  64108. * @param space The space that the rotation should be in.
  64109. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  64110. * @returns The rotation matrix
  64111. */
  64112. Bone.prototype.getRotationMatrix = function (space, mesh) {
  64113. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  64114. var result = BABYLON.Matrix.Identity();
  64115. this.getRotationMatrixToRef(space, mesh, result);
  64116. return result;
  64117. };
  64118. /**
  64119. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  64120. * @param space The space that the rotation should be in.
  64121. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  64122. * @param result The quaternion that the rotation should be copied to.
  64123. */
  64124. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  64125. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  64126. if (space == BABYLON.Space.LOCAL) {
  64127. this.getLocalMatrix().getRotationMatrixToRef(result);
  64128. }
  64129. else {
  64130. var mat = Bone._tmpMats[0];
  64131. var amat = this.getAbsoluteTransform();
  64132. if (mesh) {
  64133. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  64134. }
  64135. else {
  64136. mat.copyFrom(amat);
  64137. }
  64138. mat.m[0] *= this._scalingDeterminant;
  64139. mat.m[1] *= this._scalingDeterminant;
  64140. mat.m[2] *= this._scalingDeterminant;
  64141. mat.getRotationMatrixToRef(result);
  64142. }
  64143. };
  64144. /**
  64145. * Get the world position of a point that is in the local space of the bone.
  64146. * @param position The local position
  64147. * @param mesh The mesh that this bone is attached to.
  64148. * @returns The world position
  64149. */
  64150. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  64151. if (mesh === void 0) { mesh = null; }
  64152. var result = BABYLON.Vector3.Zero();
  64153. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  64154. return result;
  64155. };
  64156. /**
  64157. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  64158. * @param position The local position
  64159. * @param mesh The mesh that this bone is attached to.
  64160. * @param result The vector3 that the world position should be copied to.
  64161. */
  64162. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  64163. if (mesh === void 0) { mesh = null; }
  64164. var wm = null;
  64165. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  64166. if (mesh) {
  64167. wm = mesh.getWorldMatrix();
  64168. }
  64169. this._skeleton.computeAbsoluteTransforms();
  64170. var tmat = Bone._tmpMats[0];
  64171. if (mesh && wm) {
  64172. tmat.copyFrom(this.getAbsoluteTransform());
  64173. tmat.multiplyToRef(wm, tmat);
  64174. }
  64175. else {
  64176. tmat = this.getAbsoluteTransform();
  64177. }
  64178. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  64179. };
  64180. /**
  64181. * Get the local position of a point that is in world space.
  64182. * @param position The world position
  64183. * @param mesh The mesh that this bone is attached to.
  64184. * @returns The local position
  64185. */
  64186. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  64187. if (mesh === void 0) { mesh = null; }
  64188. var result = BABYLON.Vector3.Zero();
  64189. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  64190. return result;
  64191. };
  64192. /**
  64193. * Get the local position of a point that is in world space and copy it to the result param.
  64194. * @param position The world position
  64195. * @param mesh The mesh that this bone is attached to.
  64196. * @param result The vector3 that the local position should be copied to.
  64197. */
  64198. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  64199. if (mesh === void 0) { mesh = null; }
  64200. var wm = null;
  64201. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  64202. if (mesh) {
  64203. wm = mesh.getWorldMatrix();
  64204. }
  64205. this._skeleton.computeAbsoluteTransforms();
  64206. var tmat = Bone._tmpMats[0];
  64207. tmat.copyFrom(this.getAbsoluteTransform());
  64208. if (mesh && wm) {
  64209. tmat.multiplyToRef(wm, tmat);
  64210. }
  64211. tmat.invert();
  64212. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  64213. };
  64214. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64215. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  64216. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64217. return Bone;
  64218. }(BABYLON.Node));
  64219. BABYLON.Bone = Bone;
  64220. })(BABYLON || (BABYLON = {}));
  64221. //# sourceMappingURL=babylon.bone.js.map
  64222. var BABYLON;
  64223. (function (BABYLON) {
  64224. var BoneIKController = /** @class */ (function () {
  64225. function BoneIKController(mesh, bone, options) {
  64226. this.targetPosition = BABYLON.Vector3.Zero();
  64227. this.poleTargetPosition = BABYLON.Vector3.Zero();
  64228. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  64229. this.poleAngle = 0;
  64230. this.slerpAmount = 1;
  64231. this._bone1Quat = BABYLON.Quaternion.Identity();
  64232. this._bone1Mat = BABYLON.Matrix.Identity();
  64233. this._bone2Ang = Math.PI;
  64234. this._maxAngle = Math.PI;
  64235. this._rightHandedSystem = false;
  64236. this._bendAxis = BABYLON.Vector3.Right();
  64237. this._slerping = false;
  64238. this._adjustRoll = 0;
  64239. this._bone2 = bone;
  64240. this._bone1 = bone.getParent();
  64241. if (!this._bone1) {
  64242. return;
  64243. }
  64244. this.mesh = mesh;
  64245. var bonePos = bone.getPosition();
  64246. if (bone.getAbsoluteTransform().determinant() > 0) {
  64247. this._rightHandedSystem = true;
  64248. this._bendAxis.x = 0;
  64249. this._bendAxis.y = 0;
  64250. this._bendAxis.z = -1;
  64251. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  64252. this._adjustRoll = Math.PI * .5;
  64253. this._bendAxis.z = 1;
  64254. }
  64255. }
  64256. if (this._bone1.length) {
  64257. var boneScale1 = this._bone1.getScale();
  64258. var boneScale2 = this._bone2.getScale();
  64259. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  64260. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  64261. }
  64262. else if (this._bone1.children[0]) {
  64263. mesh.computeWorldMatrix(true);
  64264. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  64265. var pos2 = this._bone2.getAbsolutePosition(mesh);
  64266. var pos3 = this._bone1.getAbsolutePosition(mesh);
  64267. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  64268. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  64269. }
  64270. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  64271. this.maxAngle = Math.PI;
  64272. if (options) {
  64273. if (options.targetMesh) {
  64274. this.targetMesh = options.targetMesh;
  64275. this.targetMesh.computeWorldMatrix(true);
  64276. }
  64277. if (options.poleTargetMesh) {
  64278. this.poleTargetMesh = options.poleTargetMesh;
  64279. this.poleTargetMesh.computeWorldMatrix(true);
  64280. }
  64281. else if (options.poleTargetBone) {
  64282. this.poleTargetBone = options.poleTargetBone;
  64283. }
  64284. else if (this._bone1.getParent()) {
  64285. this.poleTargetBone = this._bone1.getParent();
  64286. }
  64287. if (options.poleTargetLocalOffset) {
  64288. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  64289. }
  64290. if (options.poleAngle) {
  64291. this.poleAngle = options.poleAngle;
  64292. }
  64293. if (options.bendAxis) {
  64294. this._bendAxis.copyFrom(options.bendAxis);
  64295. }
  64296. if (options.maxAngle) {
  64297. this.maxAngle = options.maxAngle;
  64298. }
  64299. if (options.slerpAmount) {
  64300. this.slerpAmount = options.slerpAmount;
  64301. }
  64302. }
  64303. }
  64304. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  64305. get: function () {
  64306. return this._maxAngle;
  64307. },
  64308. set: function (value) {
  64309. this._setMaxAngle(value);
  64310. },
  64311. enumerable: true,
  64312. configurable: true
  64313. });
  64314. BoneIKController.prototype._setMaxAngle = function (ang) {
  64315. if (ang < 0) {
  64316. ang = 0;
  64317. }
  64318. if (ang > Math.PI || ang == undefined) {
  64319. ang = Math.PI;
  64320. }
  64321. this._maxAngle = ang;
  64322. var a = this._bone1Length;
  64323. var b = this._bone2Length;
  64324. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  64325. };
  64326. BoneIKController.prototype.update = function () {
  64327. var bone1 = this._bone1;
  64328. if (!bone1) {
  64329. return;
  64330. }
  64331. var target = this.targetPosition;
  64332. var poleTarget = this.poleTargetPosition;
  64333. var mat1 = BoneIKController._tmpMats[0];
  64334. var mat2 = BoneIKController._tmpMats[1];
  64335. if (this.targetMesh) {
  64336. target.copyFrom(this.targetMesh.getAbsolutePosition());
  64337. }
  64338. if (this.poleTargetBone) {
  64339. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  64340. }
  64341. else if (this.poleTargetMesh) {
  64342. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  64343. }
  64344. var bonePos = BoneIKController._tmpVecs[0];
  64345. var zaxis = BoneIKController._tmpVecs[1];
  64346. var xaxis = BoneIKController._tmpVecs[2];
  64347. var yaxis = BoneIKController._tmpVecs[3];
  64348. var upAxis = BoneIKController._tmpVecs[4];
  64349. var _tmpQuat = BoneIKController._tmpQuat;
  64350. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  64351. poleTarget.subtractToRef(bonePos, upAxis);
  64352. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  64353. upAxis.y = 1;
  64354. }
  64355. else {
  64356. upAxis.normalize();
  64357. }
  64358. target.subtractToRef(bonePos, yaxis);
  64359. yaxis.normalize();
  64360. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  64361. zaxis.normalize();
  64362. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  64363. xaxis.normalize();
  64364. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  64365. var a = this._bone1Length;
  64366. var b = this._bone2Length;
  64367. var c = BABYLON.Vector3.Distance(bonePos, target);
  64368. if (this._maxReach > 0) {
  64369. c = Math.min(this._maxReach, c);
  64370. }
  64371. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  64372. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  64373. if (acosa > 1) {
  64374. acosa = 1;
  64375. }
  64376. if (acosb > 1) {
  64377. acosb = 1;
  64378. }
  64379. if (acosa < -1) {
  64380. acosa = -1;
  64381. }
  64382. if (acosb < -1) {
  64383. acosb = -1;
  64384. }
  64385. var angA = Math.acos(acosa);
  64386. var angB = Math.acos(acosb);
  64387. var angC = -angA - angB;
  64388. if (this._rightHandedSystem) {
  64389. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  64390. mat2.multiplyToRef(mat1, mat1);
  64391. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  64392. mat2.multiplyToRef(mat1, mat1);
  64393. }
  64394. else {
  64395. var _tmpVec = BoneIKController._tmpVecs[5];
  64396. _tmpVec.copyFrom(this._bendAxis);
  64397. _tmpVec.x *= -1;
  64398. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  64399. mat2.multiplyToRef(mat1, mat1);
  64400. }
  64401. if (this.poleAngle) {
  64402. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  64403. mat1.multiplyToRef(mat2, mat1);
  64404. }
  64405. if (this._bone1) {
  64406. if (this.slerpAmount < 1) {
  64407. if (!this._slerping) {
  64408. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  64409. }
  64410. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  64411. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  64412. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  64413. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  64414. this._slerping = true;
  64415. }
  64416. else {
  64417. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  64418. this._bone1Mat.copyFrom(mat1);
  64419. this._slerping = false;
  64420. }
  64421. }
  64422. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  64423. this._bone2Ang = angC;
  64424. };
  64425. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64426. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  64427. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64428. return BoneIKController;
  64429. }());
  64430. BABYLON.BoneIKController = BoneIKController;
  64431. })(BABYLON || (BABYLON = {}));
  64432. //# sourceMappingURL=babylon.boneIKController.js.map
  64433. var BABYLON;
  64434. (function (BABYLON) {
  64435. var BoneLookController = /** @class */ (function () {
  64436. /**
  64437. * Create a BoneLookController
  64438. * @param mesh the mesh that the bone belongs to
  64439. * @param bone the bone that will be looking to the target
  64440. * @param target the target Vector3 to look at
  64441. * @param settings optional settings:
  64442. * - maxYaw: the maximum angle the bone will yaw to
  64443. * - minYaw: the minimum angle the bone will yaw to
  64444. * - maxPitch: the maximum angle the bone will pitch to
  64445. * - minPitch: the minimum angle the bone will yaw to
  64446. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  64447. * - upAxis: the up axis of the coordinate system
  64448. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  64449. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  64450. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  64451. * - adjustYaw: used to make an adjustment to the yaw of the bone
  64452. * - adjustPitch: used to make an adjustment to the pitch of the bone
  64453. * - adjustRoll: used to make an adjustment to the roll of the bone
  64454. **/
  64455. function BoneLookController(mesh, bone, target, options) {
  64456. /**
  64457. * The up axis of the coordinate system that is used when the bone is rotated.
  64458. */
  64459. this.upAxis = BABYLON.Vector3.Up();
  64460. /**
  64461. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  64462. */
  64463. this.upAxisSpace = BABYLON.Space.LOCAL;
  64464. /**
  64465. * Used to make an adjustment to the yaw of the bone.
  64466. */
  64467. this.adjustYaw = 0;
  64468. /**
  64469. * Used to make an adjustment to the pitch of the bone.
  64470. */
  64471. this.adjustPitch = 0;
  64472. /**
  64473. * Used to make an adjustment to the roll of the bone.
  64474. */
  64475. this.adjustRoll = 0;
  64476. /**
  64477. * 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).
  64478. */
  64479. this.slerpAmount = 1;
  64480. this._boneQuat = BABYLON.Quaternion.Identity();
  64481. this._slerping = false;
  64482. this._firstFrameSkipped = false;
  64483. this._fowardAxis = BABYLON.Vector3.Forward();
  64484. this.mesh = mesh;
  64485. this.bone = bone;
  64486. this.target = target;
  64487. if (options) {
  64488. if (options.adjustYaw) {
  64489. this.adjustYaw = options.adjustYaw;
  64490. }
  64491. if (options.adjustPitch) {
  64492. this.adjustPitch = options.adjustPitch;
  64493. }
  64494. if (options.adjustRoll) {
  64495. this.adjustRoll = options.adjustRoll;
  64496. }
  64497. if (options.maxYaw != null) {
  64498. this.maxYaw = options.maxYaw;
  64499. }
  64500. else {
  64501. this.maxYaw = Math.PI;
  64502. }
  64503. if (options.minYaw != null) {
  64504. this.minYaw = options.minYaw;
  64505. }
  64506. else {
  64507. this.minYaw = -Math.PI;
  64508. }
  64509. if (options.maxPitch != null) {
  64510. this.maxPitch = options.maxPitch;
  64511. }
  64512. else {
  64513. this.maxPitch = Math.PI;
  64514. }
  64515. if (options.minPitch != null) {
  64516. this.minPitch = options.minPitch;
  64517. }
  64518. else {
  64519. this.minPitch = -Math.PI;
  64520. }
  64521. if (options.slerpAmount != null) {
  64522. this.slerpAmount = options.slerpAmount;
  64523. }
  64524. if (options.upAxis != null) {
  64525. this.upAxis = options.upAxis;
  64526. }
  64527. if (options.upAxisSpace != null) {
  64528. this.upAxisSpace = options.upAxisSpace;
  64529. }
  64530. if (options.yawAxis != null || options.pitchAxis != null) {
  64531. var newYawAxis = BABYLON.Axis.Y;
  64532. var newPitchAxis = BABYLON.Axis.X;
  64533. if (options.yawAxis != null) {
  64534. newYawAxis = options.yawAxis.clone();
  64535. newYawAxis.normalize();
  64536. }
  64537. if (options.pitchAxis != null) {
  64538. newPitchAxis = options.pitchAxis.clone();
  64539. newPitchAxis.normalize();
  64540. }
  64541. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  64542. this._transformYawPitch = BABYLON.Matrix.Identity();
  64543. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  64544. this._transformYawPitchInv = this._transformYawPitch.clone();
  64545. this._transformYawPitch.invert();
  64546. }
  64547. }
  64548. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  64549. this.upAxisSpace = BABYLON.Space.LOCAL;
  64550. }
  64551. }
  64552. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  64553. /**
  64554. * Get/set the minimum yaw angle that the bone can look to.
  64555. */
  64556. get: function () {
  64557. return this._minYaw;
  64558. },
  64559. set: function (value) {
  64560. this._minYaw = value;
  64561. this._minYawSin = Math.sin(value);
  64562. this._minYawCos = Math.cos(value);
  64563. if (this._maxYaw != null) {
  64564. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  64565. this._yawRange = this._maxYaw - this._minYaw;
  64566. }
  64567. },
  64568. enumerable: true,
  64569. configurable: true
  64570. });
  64571. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  64572. /**
  64573. * Get/set the maximum yaw angle that the bone can look to.
  64574. */
  64575. get: function () {
  64576. return this._maxYaw;
  64577. },
  64578. set: function (value) {
  64579. this._maxYaw = value;
  64580. this._maxYawSin = Math.sin(value);
  64581. this._maxYawCos = Math.cos(value);
  64582. if (this._minYaw != null) {
  64583. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  64584. this._yawRange = this._maxYaw - this._minYaw;
  64585. }
  64586. },
  64587. enumerable: true,
  64588. configurable: true
  64589. });
  64590. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  64591. /**
  64592. * Get/set the minimum pitch angle that the bone can look to.
  64593. */
  64594. get: function () {
  64595. return this._minPitch;
  64596. },
  64597. set: function (value) {
  64598. this._minPitch = value;
  64599. this._minPitchTan = Math.tan(value);
  64600. },
  64601. enumerable: true,
  64602. configurable: true
  64603. });
  64604. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  64605. /**
  64606. * Get/set the maximum pitch angle that the bone can look to.
  64607. */
  64608. get: function () {
  64609. return this._maxPitch;
  64610. },
  64611. set: function (value) {
  64612. this._maxPitch = value;
  64613. this._maxPitchTan = Math.tan(value);
  64614. },
  64615. enumerable: true,
  64616. configurable: true
  64617. });
  64618. /**
  64619. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  64620. */
  64621. BoneLookController.prototype.update = function () {
  64622. //skip the first frame when slerping so that the mesh rotation is correct
  64623. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  64624. this._firstFrameSkipped = true;
  64625. return;
  64626. }
  64627. var bone = this.bone;
  64628. var bonePos = BoneLookController._tmpVecs[0];
  64629. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  64630. var target = this.target;
  64631. var _tmpMat1 = BoneLookController._tmpMats[0];
  64632. var _tmpMat2 = BoneLookController._tmpMats[1];
  64633. var mesh = this.mesh;
  64634. var parentBone = bone.getParent();
  64635. var upAxis = BoneLookController._tmpVecs[1];
  64636. upAxis.copyFrom(this.upAxis);
  64637. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  64638. if (this._transformYawPitch) {
  64639. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  64640. }
  64641. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  64642. }
  64643. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  64644. mesh.getDirectionToRef(upAxis, upAxis);
  64645. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  64646. upAxis.normalize();
  64647. }
  64648. }
  64649. var checkYaw = false;
  64650. var checkPitch = false;
  64651. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  64652. checkYaw = true;
  64653. }
  64654. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  64655. checkPitch = true;
  64656. }
  64657. if (checkYaw || checkPitch) {
  64658. var spaceMat = BoneLookController._tmpMats[2];
  64659. var spaceMatInv = BoneLookController._tmpMats[3];
  64660. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  64661. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  64662. }
  64663. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  64664. spaceMat.copyFrom(mesh.getWorldMatrix());
  64665. }
  64666. else {
  64667. var forwardAxis = BoneLookController._tmpVecs[2];
  64668. forwardAxis.copyFrom(this._fowardAxis);
  64669. if (this._transformYawPitch) {
  64670. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  64671. }
  64672. if (parentBone) {
  64673. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  64674. }
  64675. else {
  64676. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  64677. }
  64678. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  64679. rightAxis.normalize();
  64680. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  64681. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  64682. }
  64683. spaceMat.invertToRef(spaceMatInv);
  64684. var xzlen = null;
  64685. if (checkPitch) {
  64686. var localTarget = BoneLookController._tmpVecs[3];
  64687. target.subtractToRef(bonePos, localTarget);
  64688. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  64689. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64690. var pitch = Math.atan2(localTarget.y, xzlen);
  64691. var newPitch = pitch;
  64692. if (pitch > this._maxPitch) {
  64693. localTarget.y = this._maxPitchTan * xzlen;
  64694. newPitch = this._maxPitch;
  64695. }
  64696. else if (pitch < this._minPitch) {
  64697. localTarget.y = this._minPitchTan * xzlen;
  64698. newPitch = this._minPitch;
  64699. }
  64700. if (pitch != newPitch) {
  64701. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  64702. localTarget.addInPlace(bonePos);
  64703. target = localTarget;
  64704. }
  64705. }
  64706. if (checkYaw) {
  64707. var localTarget = BoneLookController._tmpVecs[4];
  64708. target.subtractToRef(bonePos, localTarget);
  64709. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  64710. var yaw = Math.atan2(localTarget.x, localTarget.z);
  64711. var newYaw = yaw;
  64712. if (yaw > this._maxYaw || yaw < this._minYaw) {
  64713. if (xzlen == null) {
  64714. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64715. }
  64716. if (this._yawRange > Math.PI) {
  64717. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  64718. localTarget.z = this._maxYawCos * xzlen;
  64719. localTarget.x = this._maxYawSin * xzlen;
  64720. newYaw = this._maxYaw;
  64721. }
  64722. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  64723. localTarget.z = this._minYawCos * xzlen;
  64724. localTarget.x = this._minYawSin * xzlen;
  64725. newYaw = this._minYaw;
  64726. }
  64727. }
  64728. else {
  64729. if (yaw > this._maxYaw) {
  64730. localTarget.z = this._maxYawCos * xzlen;
  64731. localTarget.x = this._maxYawSin * xzlen;
  64732. newYaw = this._maxYaw;
  64733. }
  64734. else if (yaw < this._minYaw) {
  64735. localTarget.z = this._minYawCos * xzlen;
  64736. localTarget.x = this._minYawSin * xzlen;
  64737. newYaw = this._minYaw;
  64738. }
  64739. }
  64740. }
  64741. if (this._slerping && this._yawRange > Math.PI) {
  64742. //are we going to be crossing into the min/max region?
  64743. var boneFwd = BoneLookController._tmpVecs[8];
  64744. boneFwd.copyFrom(BABYLON.Axis.Z);
  64745. if (this._transformYawPitch) {
  64746. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  64747. }
  64748. var boneRotMat = BoneLookController._tmpMats[4];
  64749. this._boneQuat.toRotationMatrix(boneRotMat);
  64750. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  64751. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  64752. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  64753. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  64754. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  64755. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  64756. if (angBtwTar > angBtwMidYaw) {
  64757. if (xzlen == null) {
  64758. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64759. }
  64760. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  64761. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  64762. if (angBtwMin < angBtwMax) {
  64763. newYaw = boneYaw + Math.PI * .75;
  64764. localTarget.z = Math.cos(newYaw) * xzlen;
  64765. localTarget.x = Math.sin(newYaw) * xzlen;
  64766. }
  64767. else {
  64768. newYaw = boneYaw - Math.PI * .75;
  64769. localTarget.z = Math.cos(newYaw) * xzlen;
  64770. localTarget.x = Math.sin(newYaw) * xzlen;
  64771. }
  64772. }
  64773. }
  64774. if (yaw != newYaw) {
  64775. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  64776. localTarget.addInPlace(bonePos);
  64777. target = localTarget;
  64778. }
  64779. }
  64780. }
  64781. var zaxis = BoneLookController._tmpVecs[5];
  64782. var xaxis = BoneLookController._tmpVecs[6];
  64783. var yaxis = BoneLookController._tmpVecs[7];
  64784. var _tmpQuat = BoneLookController._tmpQuat;
  64785. target.subtractToRef(bonePos, zaxis);
  64786. zaxis.normalize();
  64787. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  64788. xaxis.normalize();
  64789. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  64790. yaxis.normalize();
  64791. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  64792. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  64793. return;
  64794. }
  64795. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  64796. return;
  64797. }
  64798. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  64799. return;
  64800. }
  64801. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  64802. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  64803. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  64804. }
  64805. if (this.slerpAmount < 1) {
  64806. if (!this._slerping) {
  64807. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  64808. }
  64809. if (this._transformYawPitch) {
  64810. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  64811. }
  64812. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  64813. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  64814. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  64815. this._slerping = true;
  64816. }
  64817. else {
  64818. if (this._transformYawPitch) {
  64819. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  64820. }
  64821. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  64822. this._slerping = false;
  64823. }
  64824. };
  64825. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  64826. var angDiff = ang2 - ang1;
  64827. angDiff %= Math.PI * 2;
  64828. if (angDiff > Math.PI) {
  64829. angDiff -= Math.PI * 2;
  64830. }
  64831. else if (angDiff < -Math.PI) {
  64832. angDiff += Math.PI * 2;
  64833. }
  64834. return angDiff;
  64835. };
  64836. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  64837. ang1 %= (2 * Math.PI);
  64838. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  64839. ang2 %= (2 * Math.PI);
  64840. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  64841. var ab = 0;
  64842. if (ang1 < ang2) {
  64843. ab = ang2 - ang1;
  64844. }
  64845. else {
  64846. ab = ang1 - ang2;
  64847. }
  64848. if (ab > Math.PI) {
  64849. ab = Math.PI * 2 - ab;
  64850. }
  64851. return ab;
  64852. };
  64853. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  64854. ang %= (2 * Math.PI);
  64855. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  64856. ang1 %= (2 * Math.PI);
  64857. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  64858. ang2 %= (2 * Math.PI);
  64859. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  64860. if (ang1 < ang2) {
  64861. if (ang > ang1 && ang < ang2) {
  64862. return true;
  64863. }
  64864. }
  64865. else {
  64866. if (ang > ang2 && ang < ang1) {
  64867. return true;
  64868. }
  64869. }
  64870. return false;
  64871. };
  64872. 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()];
  64873. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  64874. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64875. return BoneLookController;
  64876. }());
  64877. BABYLON.BoneLookController = BoneLookController;
  64878. })(BABYLON || (BABYLON = {}));
  64879. //# sourceMappingURL=babylon.boneLookController.js.map
  64880. var BABYLON;
  64881. (function (BABYLON) {
  64882. var Skeleton = /** @class */ (function () {
  64883. function Skeleton(name, id, scene) {
  64884. this.name = name;
  64885. this.id = id;
  64886. this.bones = new Array();
  64887. this.needInitialSkinMatrix = false;
  64888. this._isDirty = true;
  64889. this._meshesWithPoseMatrix = new Array();
  64890. this._identity = BABYLON.Matrix.Identity();
  64891. this._ranges = {};
  64892. this._lastAbsoluteTransformsUpdateId = -1;
  64893. // Events
  64894. /**
  64895. * An event triggered before computing the skeleton's matrices
  64896. * @type {BABYLON.Observable}
  64897. */
  64898. this.onBeforeComputeObservable = new BABYLON.Observable();
  64899. this.bones = [];
  64900. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64901. scene.skeletons.push(this);
  64902. //make sure it will recalculate the matrix next time prepare is called.
  64903. this._isDirty = true;
  64904. }
  64905. // Members
  64906. Skeleton.prototype.getTransformMatrices = function (mesh) {
  64907. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  64908. return mesh._bonesTransformMatrices;
  64909. }
  64910. if (!this._transformMatrices) {
  64911. this.prepare();
  64912. }
  64913. return this._transformMatrices;
  64914. };
  64915. Skeleton.prototype.getScene = function () {
  64916. return this._scene;
  64917. };
  64918. // Methods
  64919. /**
  64920. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  64921. */
  64922. Skeleton.prototype.toString = function (fullDetails) {
  64923. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  64924. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  64925. if (fullDetails) {
  64926. ret += ", Ranges: {";
  64927. var first = true;
  64928. for (var name_1 in this._ranges) {
  64929. if (first) {
  64930. ret += ", ";
  64931. first = false;
  64932. }
  64933. ret += name_1;
  64934. }
  64935. ret += "}";
  64936. }
  64937. return ret;
  64938. };
  64939. /**
  64940. * Get bone's index searching by name
  64941. * @param {string} name is bone's name to search for
  64942. * @return {number} Indice of the bone. Returns -1 if not found
  64943. */
  64944. Skeleton.prototype.getBoneIndexByName = function (name) {
  64945. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  64946. if (this.bones[boneIndex].name === name) {
  64947. return boneIndex;
  64948. }
  64949. }
  64950. return -1;
  64951. };
  64952. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  64953. // check name not already in use
  64954. if (!this._ranges[name]) {
  64955. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  64956. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64957. if (this.bones[i].animations[0]) {
  64958. this.bones[i].animations[0].createRange(name, from, to);
  64959. }
  64960. }
  64961. }
  64962. };
  64963. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  64964. if (deleteFrames === void 0) { deleteFrames = true; }
  64965. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64966. if (this.bones[i].animations[0]) {
  64967. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  64968. }
  64969. }
  64970. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  64971. };
  64972. Skeleton.prototype.getAnimationRange = function (name) {
  64973. return this._ranges[name];
  64974. };
  64975. /**
  64976. * Returns as an Array, all AnimationRanges defined on this skeleton
  64977. */
  64978. Skeleton.prototype.getAnimationRanges = function () {
  64979. var animationRanges = [];
  64980. var name;
  64981. var i = 0;
  64982. for (name in this._ranges) {
  64983. animationRanges[i] = this._ranges[name];
  64984. i++;
  64985. }
  64986. return animationRanges;
  64987. };
  64988. /**
  64989. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  64990. */
  64991. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  64992. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  64993. if (this._ranges[name] || !source.getAnimationRange(name)) {
  64994. return false;
  64995. }
  64996. var ret = true;
  64997. var frameOffset = this._getHighestAnimationFrame() + 1;
  64998. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  64999. var boneDict = {};
  65000. var sourceBones = source.bones;
  65001. var nBones;
  65002. var i;
  65003. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  65004. boneDict[sourceBones[i].name] = sourceBones[i];
  65005. }
  65006. if (this.bones.length !== sourceBones.length) {
  65007. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  65008. ret = false;
  65009. }
  65010. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  65011. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  65012. var boneName = this.bones[i].name;
  65013. var sourceBone = boneDict[boneName];
  65014. if (sourceBone) {
  65015. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  65016. }
  65017. else {
  65018. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  65019. ret = false;
  65020. }
  65021. }
  65022. // do not call createAnimationRange(), since it also is done to bones, which was already done
  65023. var range = source.getAnimationRange(name);
  65024. if (range) {
  65025. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  65026. }
  65027. return ret;
  65028. };
  65029. Skeleton.prototype.returnToRest = function () {
  65030. for (var index = 0; index < this.bones.length; index++) {
  65031. this.bones[index].returnToRest();
  65032. }
  65033. };
  65034. Skeleton.prototype._getHighestAnimationFrame = function () {
  65035. var ret = 0;
  65036. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  65037. if (this.bones[i].animations[0]) {
  65038. var highest = this.bones[i].animations[0].getHighestFrame();
  65039. if (ret < highest) {
  65040. ret = highest;
  65041. }
  65042. }
  65043. }
  65044. return ret;
  65045. };
  65046. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  65047. var range = this.getAnimationRange(name);
  65048. if (!range) {
  65049. return null;
  65050. }
  65051. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  65052. };
  65053. Skeleton.prototype._markAsDirty = function () {
  65054. this._isDirty = true;
  65055. };
  65056. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  65057. this._meshesWithPoseMatrix.push(mesh);
  65058. };
  65059. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  65060. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  65061. if (index > -1) {
  65062. this._meshesWithPoseMatrix.splice(index, 1);
  65063. }
  65064. };
  65065. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  65066. this.onBeforeComputeObservable.notifyObservers(this);
  65067. for (var index = 0; index < this.bones.length; index++) {
  65068. var bone = this.bones[index];
  65069. var parentBone = bone.getParent();
  65070. if (parentBone) {
  65071. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  65072. }
  65073. else {
  65074. if (initialSkinMatrix) {
  65075. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  65076. }
  65077. else {
  65078. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  65079. }
  65080. }
  65081. if (bone._index !== -1) {
  65082. var mappedIndex = bone._index === null ? index : bone._index;
  65083. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  65084. }
  65085. }
  65086. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  65087. };
  65088. Skeleton.prototype.prepare = function () {
  65089. if (!this._isDirty) {
  65090. return;
  65091. }
  65092. if (this.needInitialSkinMatrix) {
  65093. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  65094. var mesh = this._meshesWithPoseMatrix[index];
  65095. var poseMatrix = mesh.getPoseMatrix();
  65096. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  65097. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  65098. }
  65099. if (this._synchronizedWithMesh !== mesh) {
  65100. this._synchronizedWithMesh = mesh;
  65101. // Prepare bones
  65102. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  65103. var bone = this.bones[boneIndex];
  65104. if (!bone.getParent()) {
  65105. var matrix = bone.getBaseMatrix();
  65106. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  65107. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  65108. }
  65109. }
  65110. }
  65111. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  65112. }
  65113. }
  65114. else {
  65115. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  65116. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  65117. }
  65118. this._computeTransformMatrices(this._transformMatrices, null);
  65119. }
  65120. this._isDirty = false;
  65121. this._scene._activeBones.addCount(this.bones.length, false);
  65122. };
  65123. Skeleton.prototype.getAnimatables = function () {
  65124. if (!this._animatables || this._animatables.length !== this.bones.length) {
  65125. this._animatables = [];
  65126. for (var index = 0; index < this.bones.length; index++) {
  65127. this._animatables.push(this.bones[index]);
  65128. }
  65129. }
  65130. return this._animatables;
  65131. };
  65132. Skeleton.prototype.clone = function (name, id) {
  65133. var result = new Skeleton(name, id || name, this._scene);
  65134. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  65135. for (var index = 0; index < this.bones.length; index++) {
  65136. var source = this.bones[index];
  65137. var parentBone = null;
  65138. var parent_1 = source.getParent();
  65139. if (parent_1) {
  65140. var parentIndex = this.bones.indexOf(parent_1);
  65141. parentBone = result.bones[parentIndex];
  65142. }
  65143. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  65144. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  65145. }
  65146. if (this._ranges) {
  65147. result._ranges = {};
  65148. for (var rangeName in this._ranges) {
  65149. var range = this._ranges[rangeName];
  65150. if (range) {
  65151. result._ranges[rangeName] = range.clone();
  65152. }
  65153. }
  65154. }
  65155. this._isDirty = true;
  65156. return result;
  65157. };
  65158. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  65159. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  65160. this.bones.forEach(function (bone) {
  65161. bone.animations.forEach(function (animation) {
  65162. animation.enableBlending = true;
  65163. animation.blendingSpeed = blendingSpeed;
  65164. });
  65165. });
  65166. };
  65167. Skeleton.prototype.dispose = function () {
  65168. this._meshesWithPoseMatrix = [];
  65169. // Animations
  65170. this.getScene().stopAnimation(this);
  65171. // Remove from scene
  65172. this.getScene().removeSkeleton(this);
  65173. };
  65174. Skeleton.prototype.serialize = function () {
  65175. var serializationObject = {};
  65176. serializationObject.name = this.name;
  65177. serializationObject.id = this.id;
  65178. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  65179. serializationObject.bones = [];
  65180. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  65181. for (var index = 0; index < this.bones.length; index++) {
  65182. var bone = this.bones[index];
  65183. var parent_2 = bone.getParent();
  65184. var serializedBone = {
  65185. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  65186. name: bone.name,
  65187. matrix: bone.getBaseMatrix().toArray(),
  65188. rest: bone.getRestPose().toArray()
  65189. };
  65190. serializationObject.bones.push(serializedBone);
  65191. if (bone.length) {
  65192. serializedBone.length = bone.length;
  65193. }
  65194. if (bone.animations && bone.animations.length > 0) {
  65195. serializedBone.animation = bone.animations[0].serialize();
  65196. }
  65197. serializationObject.ranges = [];
  65198. for (var name in this._ranges) {
  65199. var source = this._ranges[name];
  65200. if (!source) {
  65201. continue;
  65202. }
  65203. var range = {};
  65204. range.name = name;
  65205. range.from = source.from;
  65206. range.to = source.to;
  65207. serializationObject.ranges.push(range);
  65208. }
  65209. }
  65210. return serializationObject;
  65211. };
  65212. Skeleton.Parse = function (parsedSkeleton, scene) {
  65213. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  65214. if (parsedSkeleton.dimensionsAtRest) {
  65215. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  65216. }
  65217. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  65218. var index;
  65219. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  65220. var parsedBone = parsedSkeleton.bones[index];
  65221. var parentBone = null;
  65222. if (parsedBone.parentBoneIndex > -1) {
  65223. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  65224. }
  65225. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  65226. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  65227. if (parsedBone.length) {
  65228. bone.length = parsedBone.length;
  65229. }
  65230. if (parsedBone.animation) {
  65231. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  65232. }
  65233. }
  65234. // placed after bones, so createAnimationRange can cascade down
  65235. if (parsedSkeleton.ranges) {
  65236. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  65237. var data = parsedSkeleton.ranges[index];
  65238. skeleton.createAnimationRange(data.name, data.from, data.to);
  65239. }
  65240. }
  65241. return skeleton;
  65242. };
  65243. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  65244. if (forceUpdate === void 0) { forceUpdate = false; }
  65245. var renderId = this._scene.getRenderId();
  65246. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  65247. this.bones[0].computeAbsoluteTransforms();
  65248. this._lastAbsoluteTransformsUpdateId = renderId;
  65249. }
  65250. };
  65251. Skeleton.prototype.getPoseMatrix = function () {
  65252. var poseMatrix = null;
  65253. if (this._meshesWithPoseMatrix.length > 0) {
  65254. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  65255. }
  65256. return poseMatrix;
  65257. };
  65258. Skeleton.prototype.sortBones = function () {
  65259. var bones = new Array();
  65260. var visited = new Array(this.bones.length);
  65261. for (var index = 0; index < this.bones.length; index++) {
  65262. this._sortBones(index, bones, visited);
  65263. }
  65264. this.bones = bones;
  65265. };
  65266. Skeleton.prototype._sortBones = function (index, bones, visited) {
  65267. if (visited[index]) {
  65268. return;
  65269. }
  65270. visited[index] = true;
  65271. var bone = this.bones[index];
  65272. if (bone._index === undefined) {
  65273. bone._index = index;
  65274. }
  65275. var parentBone = bone.getParent();
  65276. if (parentBone) {
  65277. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  65278. }
  65279. bones.push(bone);
  65280. };
  65281. return Skeleton;
  65282. }());
  65283. BABYLON.Skeleton = Skeleton;
  65284. })(BABYLON || (BABYLON = {}));
  65285. //# sourceMappingURL=babylon.skeleton.js.map
  65286. var BABYLON;
  65287. (function (BABYLON) {
  65288. var SphericalPolynomial = /** @class */ (function () {
  65289. function SphericalPolynomial() {
  65290. this.x = BABYLON.Vector3.Zero();
  65291. this.y = BABYLON.Vector3.Zero();
  65292. this.z = BABYLON.Vector3.Zero();
  65293. this.xx = BABYLON.Vector3.Zero();
  65294. this.yy = BABYLON.Vector3.Zero();
  65295. this.zz = BABYLON.Vector3.Zero();
  65296. this.xy = BABYLON.Vector3.Zero();
  65297. this.yz = BABYLON.Vector3.Zero();
  65298. this.zx = BABYLON.Vector3.Zero();
  65299. }
  65300. SphericalPolynomial.prototype.addAmbient = function (color) {
  65301. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  65302. this.xx = this.xx.add(colorVector);
  65303. this.yy = this.yy.add(colorVector);
  65304. this.zz = this.zz.add(colorVector);
  65305. };
  65306. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  65307. var result = new SphericalPolynomial();
  65308. result.x = harmonics.L11.scale(1.02333);
  65309. result.y = harmonics.L1_1.scale(1.02333);
  65310. result.z = harmonics.L10.scale(1.02333);
  65311. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  65312. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  65313. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  65314. result.yz = harmonics.L2_1.scale(0.858086);
  65315. result.zx = harmonics.L21.scale(0.858086);
  65316. result.xy = harmonics.L2_2.scale(0.858086);
  65317. result.scale(1.0 / Math.PI);
  65318. return result;
  65319. };
  65320. SphericalPolynomial.prototype.scale = function (scale) {
  65321. this.x = this.x.scale(scale);
  65322. this.y = this.y.scale(scale);
  65323. this.z = this.z.scale(scale);
  65324. this.xx = this.xx.scale(scale);
  65325. this.yy = this.yy.scale(scale);
  65326. this.zz = this.zz.scale(scale);
  65327. this.yz = this.yz.scale(scale);
  65328. this.zx = this.zx.scale(scale);
  65329. this.xy = this.xy.scale(scale);
  65330. };
  65331. return SphericalPolynomial;
  65332. }());
  65333. BABYLON.SphericalPolynomial = SphericalPolynomial;
  65334. var SphericalHarmonics = /** @class */ (function () {
  65335. function SphericalHarmonics() {
  65336. this.L00 = BABYLON.Vector3.Zero();
  65337. this.L1_1 = BABYLON.Vector3.Zero();
  65338. this.L10 = BABYLON.Vector3.Zero();
  65339. this.L11 = BABYLON.Vector3.Zero();
  65340. this.L2_2 = BABYLON.Vector3.Zero();
  65341. this.L2_1 = BABYLON.Vector3.Zero();
  65342. this.L20 = BABYLON.Vector3.Zero();
  65343. this.L21 = BABYLON.Vector3.Zero();
  65344. this.L22 = BABYLON.Vector3.Zero();
  65345. }
  65346. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  65347. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  65348. var c = colorVector.scale(deltaSolidAngle);
  65349. this.L00 = this.L00.add(c.scale(0.282095));
  65350. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  65351. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  65352. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  65353. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  65354. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  65355. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  65356. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  65357. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  65358. };
  65359. SphericalHarmonics.prototype.scale = function (scale) {
  65360. this.L00 = this.L00.scale(scale);
  65361. this.L1_1 = this.L1_1.scale(scale);
  65362. this.L10 = this.L10.scale(scale);
  65363. this.L11 = this.L11.scale(scale);
  65364. this.L2_2 = this.L2_2.scale(scale);
  65365. this.L2_1 = this.L2_1.scale(scale);
  65366. this.L20 = this.L20.scale(scale);
  65367. this.L21 = this.L21.scale(scale);
  65368. this.L22 = this.L22.scale(scale);
  65369. };
  65370. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  65371. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  65372. //
  65373. // E_lm = A_l * L_lm
  65374. //
  65375. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  65376. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  65377. // the scaling factors are given in equation 9.
  65378. // Constant (Band 0)
  65379. this.L00 = this.L00.scale(3.141593);
  65380. // Linear (Band 1)
  65381. this.L1_1 = this.L1_1.scale(2.094395);
  65382. this.L10 = this.L10.scale(2.094395);
  65383. this.L11 = this.L11.scale(2.094395);
  65384. // Quadratic (Band 2)
  65385. this.L2_2 = this.L2_2.scale(0.785398);
  65386. this.L2_1 = this.L2_1.scale(0.785398);
  65387. this.L20 = this.L20.scale(0.785398);
  65388. this.L21 = this.L21.scale(0.785398);
  65389. this.L22 = this.L22.scale(0.785398);
  65390. };
  65391. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  65392. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  65393. // L = (1/pi) * E * rho
  65394. //
  65395. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  65396. this.scale(1.0 / Math.PI);
  65397. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  65398. // (The pixel shader must apply albedo after texture fetches, etc).
  65399. };
  65400. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  65401. var result = new SphericalHarmonics();
  65402. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  65403. result.L1_1 = polynomial.y.scale(0.977204);
  65404. result.L10 = polynomial.z.scale(0.977204);
  65405. result.L11 = polynomial.x.scale(0.977204);
  65406. result.L2_2 = polynomial.xy.scale(1.16538);
  65407. result.L2_1 = polynomial.yz.scale(1.16538);
  65408. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  65409. result.L21 = polynomial.zx.scale(1.16538);
  65410. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  65411. result.scale(Math.PI);
  65412. return result;
  65413. };
  65414. return SphericalHarmonics;
  65415. }());
  65416. BABYLON.SphericalHarmonics = SphericalHarmonics;
  65417. })(BABYLON || (BABYLON = {}));
  65418. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  65419. var BABYLON;
  65420. (function (BABYLON) {
  65421. var FileFaceOrientation = /** @class */ (function () {
  65422. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  65423. this.name = name;
  65424. this.worldAxisForNormal = worldAxisForNormal;
  65425. this.worldAxisForFileX = worldAxisForFileX;
  65426. this.worldAxisForFileY = worldAxisForFileY;
  65427. }
  65428. return FileFaceOrientation;
  65429. }());
  65430. ;
  65431. /**
  65432. * Helper class dealing with the extraction of spherical polynomial dataArray
  65433. * from a cube map.
  65434. */
  65435. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  65436. function CubeMapToSphericalPolynomialTools() {
  65437. }
  65438. /**
  65439. * Converts a texture to the according Spherical Polynomial data.
  65440. * This extracts the first 3 orders only as they are the only one used in the lighting.
  65441. *
  65442. * @param texture The texture to extract the information from.
  65443. * @return The Spherical Polynomial data.
  65444. */
  65445. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  65446. if (!texture.isCube) {
  65447. // Only supports cube Textures currently.
  65448. return null;
  65449. }
  65450. var size = texture.getSize().width;
  65451. var right = texture.readPixels(0);
  65452. var left = texture.readPixels(1);
  65453. var up;
  65454. var down;
  65455. if (texture.isRenderTarget) {
  65456. up = texture.readPixels(3);
  65457. down = texture.readPixels(2);
  65458. }
  65459. else {
  65460. up = texture.readPixels(2);
  65461. down = texture.readPixels(3);
  65462. }
  65463. var front = texture.readPixels(4);
  65464. var back = texture.readPixels(5);
  65465. var gammaSpace = texture.gammaSpace;
  65466. // Always read as RGBA.
  65467. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  65468. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65469. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65470. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65471. }
  65472. var cubeInfo = {
  65473. size: size,
  65474. right: right,
  65475. left: left,
  65476. up: up,
  65477. down: down,
  65478. front: front,
  65479. back: back,
  65480. format: format,
  65481. type: type,
  65482. gammaSpace: gammaSpace,
  65483. };
  65484. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  65485. };
  65486. /**
  65487. * Converts a cubemap to the according Spherical Polynomial data.
  65488. * This extracts the first 3 orders only as they are the only one used in the lighting.
  65489. *
  65490. * @param cubeInfo The Cube map to extract the information from.
  65491. * @return The Spherical Polynomial data.
  65492. */
  65493. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  65494. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  65495. var totalSolidAngle = 0.0;
  65496. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  65497. var du = 2.0 / cubeInfo.size;
  65498. var dv = du;
  65499. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  65500. var minUV = du * 0.5 - 1.0;
  65501. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65502. var fileFace = this.FileFaces[faceIndex];
  65503. var dataArray = cubeInfo[fileFace.name];
  65504. var v = minUV;
  65505. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  65506. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  65507. // Because SP is still linear, so summation is fine in that basis.
  65508. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  65509. for (var y = 0; y < cubeInfo.size; y++) {
  65510. var u = minUV;
  65511. for (var x = 0; x < cubeInfo.size; x++) {
  65512. // World direction (not normalised)
  65513. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  65514. worldDirection.normalize();
  65515. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  65516. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  65517. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  65518. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  65519. // Handle Integer types.
  65520. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65521. r /= 255;
  65522. g /= 255;
  65523. b /= 255;
  65524. }
  65525. // Handle Gamma space textures.
  65526. if (cubeInfo.gammaSpace) {
  65527. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  65528. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  65529. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  65530. }
  65531. var color = new BABYLON.Color3(r, g, b);
  65532. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  65533. totalSolidAngle += deltaSolidAngle;
  65534. u += du;
  65535. }
  65536. v += dv;
  65537. }
  65538. }
  65539. // Solid angle for entire sphere is 4*pi
  65540. var sphereSolidAngle = 4.0 * Math.PI;
  65541. // Adjust the solid angle to allow for how many faces we processed.
  65542. var facesProcessed = 6.0;
  65543. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  65544. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  65545. // This is needed because the numerical integration over the cube uses a
  65546. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  65547. // and also to compensate for accumulative error due to float precision in the summation.
  65548. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  65549. sphericalHarmonics.scale(correctionFactor);
  65550. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  65551. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  65552. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  65553. };
  65554. CubeMapToSphericalPolynomialTools.FileFaces = [
  65555. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  65556. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  65557. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  65558. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  65559. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  65560. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  65561. ];
  65562. return CubeMapToSphericalPolynomialTools;
  65563. }());
  65564. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  65565. })(BABYLON || (BABYLON = {}));
  65566. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  65567. var BABYLON;
  65568. (function (BABYLON) {
  65569. /**
  65570. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  65571. */
  65572. var PanoramaToCubeMapTools = /** @class */ (function () {
  65573. function PanoramaToCubeMapTools() {
  65574. }
  65575. /**
  65576. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  65577. *
  65578. * @param float32Array The source data.
  65579. * @param inputWidth The width of the input panorama.
  65580. * @param inputhHeight The height of the input panorama.
  65581. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  65582. * @return The cubemap data
  65583. */
  65584. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  65585. if (!float32Array) {
  65586. throw "ConvertPanoramaToCubemap: input cannot be null";
  65587. }
  65588. if (float32Array.length != inputWidth * inputHeight * 3) {
  65589. throw "ConvertPanoramaToCubemap: input size is wrong";
  65590. }
  65591. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  65592. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  65593. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  65594. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  65595. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  65596. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  65597. return {
  65598. front: textureFront,
  65599. back: textureBack,
  65600. left: textureLeft,
  65601. right: textureRight,
  65602. up: textureUp,
  65603. down: textureDown,
  65604. size: size,
  65605. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  65606. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  65607. gammaSpace: false,
  65608. };
  65609. };
  65610. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  65611. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  65612. var textureArray = new Float32Array(buffer);
  65613. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  65614. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  65615. var dy = 1 / texSize;
  65616. var fy = 0;
  65617. for (var y = 0; y < texSize; y++) {
  65618. var xv1 = faceData[0];
  65619. var xv2 = faceData[2];
  65620. for (var x = 0; x < texSize; x++) {
  65621. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  65622. v.normalize();
  65623. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  65624. // 3 channels per pixels
  65625. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  65626. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  65627. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  65628. xv1 = xv1.add(rotDX1);
  65629. xv2 = xv2.add(rotDX2);
  65630. }
  65631. fy += dy;
  65632. }
  65633. return textureArray;
  65634. };
  65635. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  65636. var theta = Math.atan2(vDir.z, vDir.x);
  65637. var phi = Math.acos(vDir.y);
  65638. while (theta < -Math.PI)
  65639. theta += 2 * Math.PI;
  65640. while (theta > Math.PI)
  65641. theta -= 2 * Math.PI;
  65642. var dx = theta / Math.PI;
  65643. var dy = phi / Math.PI;
  65644. // recenter.
  65645. dx = dx * 0.5 + 0.5;
  65646. var px = Math.round(dx * inputWidth);
  65647. if (px < 0)
  65648. px = 0;
  65649. else if (px >= inputWidth)
  65650. px = inputWidth - 1;
  65651. var py = Math.round(dy * inputHeight);
  65652. if (py < 0)
  65653. py = 0;
  65654. else if (py >= inputHeight)
  65655. py = inputHeight - 1;
  65656. var inputY = (inputHeight - py - 1);
  65657. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  65658. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  65659. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  65660. return {
  65661. r: r,
  65662. g: g,
  65663. b: b
  65664. };
  65665. };
  65666. PanoramaToCubeMapTools.FACE_FRONT = [
  65667. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65668. new BABYLON.Vector3(1.0, -1.0, -1.0),
  65669. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  65670. new BABYLON.Vector3(1.0, 1.0, -1.0)
  65671. ];
  65672. PanoramaToCubeMapTools.FACE_BACK = [
  65673. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65674. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65675. new BABYLON.Vector3(1.0, 1.0, 1.0),
  65676. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  65677. ];
  65678. PanoramaToCubeMapTools.FACE_RIGHT = [
  65679. new BABYLON.Vector3(1.0, -1.0, -1.0),
  65680. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65681. new BABYLON.Vector3(1.0, 1.0, -1.0),
  65682. new BABYLON.Vector3(1.0, 1.0, 1.0)
  65683. ];
  65684. PanoramaToCubeMapTools.FACE_LEFT = [
  65685. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65686. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65687. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  65688. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  65689. ];
  65690. PanoramaToCubeMapTools.FACE_DOWN = [
  65691. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  65692. new BABYLON.Vector3(1.0, 1.0, -1.0),
  65693. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  65694. new BABYLON.Vector3(1.0, 1.0, 1.0)
  65695. ];
  65696. PanoramaToCubeMapTools.FACE_UP = [
  65697. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65698. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65699. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65700. new BABYLON.Vector3(1.0, -1.0, -1.0)
  65701. ];
  65702. return PanoramaToCubeMapTools;
  65703. }());
  65704. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  65705. })(BABYLON || (BABYLON = {}));
  65706. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  65707. var BABYLON;
  65708. (function (BABYLON) {
  65709. ;
  65710. /**
  65711. * This groups tools to convert HDR texture to native colors array.
  65712. */
  65713. var HDRTools = /** @class */ (function () {
  65714. function HDRTools() {
  65715. }
  65716. HDRTools.Ldexp = function (mantissa, exponent) {
  65717. if (exponent > 1023) {
  65718. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  65719. }
  65720. if (exponent < -1074) {
  65721. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  65722. }
  65723. return mantissa * Math.pow(2, exponent);
  65724. };
  65725. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  65726. if (exponent > 0) {
  65727. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  65728. float32array[index + 0] = red * exponent;
  65729. float32array[index + 1] = green * exponent;
  65730. float32array[index + 2] = blue * exponent;
  65731. }
  65732. else {
  65733. float32array[index + 0] = 0;
  65734. float32array[index + 1] = 0;
  65735. float32array[index + 2] = 0;
  65736. }
  65737. };
  65738. HDRTools.readStringLine = function (uint8array, startIndex) {
  65739. var line = "";
  65740. var character = "";
  65741. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  65742. character = String.fromCharCode(uint8array[i]);
  65743. if (character == "\n") {
  65744. break;
  65745. }
  65746. line += character;
  65747. }
  65748. return line;
  65749. };
  65750. /**
  65751. * Reads header information from an RGBE texture stored in a native array.
  65752. * More information on this format are available here:
  65753. * https://en.wikipedia.org/wiki/RGBE_image_format
  65754. *
  65755. * @param uint8array The binary file stored in native array.
  65756. * @return The header information.
  65757. */
  65758. HDRTools.RGBE_ReadHeader = function (uint8array) {
  65759. var height = 0;
  65760. var width = 0;
  65761. var line = this.readStringLine(uint8array, 0);
  65762. if (line[0] != '#' || line[1] != '?') {
  65763. throw "Bad HDR Format.";
  65764. }
  65765. var endOfHeader = false;
  65766. var findFormat = false;
  65767. var lineIndex = 0;
  65768. do {
  65769. lineIndex += (line.length + 1);
  65770. line = this.readStringLine(uint8array, lineIndex);
  65771. if (line == "FORMAT=32-bit_rle_rgbe") {
  65772. findFormat = true;
  65773. }
  65774. else if (line.length == 0) {
  65775. endOfHeader = true;
  65776. }
  65777. } while (!endOfHeader);
  65778. if (!findFormat) {
  65779. throw "HDR Bad header format, unsupported FORMAT";
  65780. }
  65781. lineIndex += (line.length + 1);
  65782. line = this.readStringLine(uint8array, lineIndex);
  65783. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  65784. var match = sizeRegexp.exec(line);
  65785. // TODO. Support +Y and -X if needed.
  65786. if (!match || match.length < 3) {
  65787. throw "HDR Bad header format, no size";
  65788. }
  65789. width = parseInt(match[2]);
  65790. height = parseInt(match[1]);
  65791. if (width < 8 || width > 0x7fff) {
  65792. throw "HDR Bad header format, unsupported size";
  65793. }
  65794. lineIndex += (line.length + 1);
  65795. return {
  65796. height: height,
  65797. width: width,
  65798. dataPosition: lineIndex
  65799. };
  65800. };
  65801. /**
  65802. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  65803. * This RGBE texture needs to store the information as a panorama.
  65804. *
  65805. * More information on this format are available here:
  65806. * https://en.wikipedia.org/wiki/RGBE_image_format
  65807. *
  65808. * @param buffer The binary file stored in an array buffer.
  65809. * @param size The expected size of the extracted cubemap.
  65810. * @return The Cube Map information.
  65811. */
  65812. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  65813. var uint8array = new Uint8Array(buffer);
  65814. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  65815. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  65816. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  65817. return cubeMapData;
  65818. };
  65819. /**
  65820. * Returns the pixels data extracted from an RGBE texture.
  65821. * This pixels will be stored left to right up to down in the R G B order in one array.
  65822. *
  65823. * More information on this format are available here:
  65824. * https://en.wikipedia.org/wiki/RGBE_image_format
  65825. *
  65826. * @param uint8array The binary file stored in an array buffer.
  65827. * @param hdrInfo The header information of the file.
  65828. * @return The pixels data in RGB right to left up to down order.
  65829. */
  65830. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  65831. // Keep for multi format supports.
  65832. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  65833. };
  65834. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  65835. var num_scanlines = hdrInfo.height;
  65836. var scanline_width = hdrInfo.width;
  65837. var a, b, c, d, count;
  65838. var dataIndex = hdrInfo.dataPosition;
  65839. var index = 0, endIndex = 0, i = 0;
  65840. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  65841. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  65842. // 3 channels of 4 bytes per pixel in float.
  65843. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  65844. var resultArray = new Float32Array(resultBuffer);
  65845. // read in each successive scanline
  65846. while (num_scanlines > 0) {
  65847. a = uint8array[dataIndex++];
  65848. b = uint8array[dataIndex++];
  65849. c = uint8array[dataIndex++];
  65850. d = uint8array[dataIndex++];
  65851. if (a != 2 || b != 2 || (c & 0x80)) {
  65852. // this file is not run length encoded
  65853. throw "HDR Bad header format, not RLE";
  65854. }
  65855. if (((c << 8) | d) != scanline_width) {
  65856. throw "HDR Bad header format, wrong scan line width";
  65857. }
  65858. index = 0;
  65859. // read each of the four channels for the scanline into the buffer
  65860. for (i = 0; i < 4; i++) {
  65861. endIndex = (i + 1) * scanline_width;
  65862. while (index < endIndex) {
  65863. a = uint8array[dataIndex++];
  65864. b = uint8array[dataIndex++];
  65865. if (a > 128) {
  65866. // a run of the same value
  65867. count = a - 128;
  65868. if ((count == 0) || (count > endIndex - index)) {
  65869. throw "HDR Bad Format, bad scanline data (run)";
  65870. }
  65871. while (count-- > 0) {
  65872. scanLineArray[index++] = b;
  65873. }
  65874. }
  65875. else {
  65876. // a non-run
  65877. count = a;
  65878. if ((count == 0) || (count > endIndex - index)) {
  65879. throw "HDR Bad Format, bad scanline data (non-run)";
  65880. }
  65881. scanLineArray[index++] = b;
  65882. if (--count > 0) {
  65883. for (var j = 0; j < count; j++) {
  65884. scanLineArray[index++] = uint8array[dataIndex++];
  65885. }
  65886. }
  65887. }
  65888. }
  65889. }
  65890. // now convert data from buffer into floats
  65891. for (i = 0; i < scanline_width; i++) {
  65892. a = scanLineArray[i];
  65893. b = scanLineArray[i + scanline_width];
  65894. c = scanLineArray[i + 2 * scanline_width];
  65895. d = scanLineArray[i + 3 * scanline_width];
  65896. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  65897. }
  65898. num_scanlines--;
  65899. }
  65900. return resultArray;
  65901. };
  65902. return HDRTools;
  65903. }());
  65904. BABYLON.HDRTools = HDRTools;
  65905. })(BABYLON || (BABYLON = {}));
  65906. //# sourceMappingURL=babylon.hdr.js.map
  65907. var BABYLON;
  65908. (function (BABYLON) {
  65909. /**
  65910. * This represents a texture coming from an HDR input.
  65911. *
  65912. * The only supported format is currently panorama picture stored in RGBE format.
  65913. * Example of such files can be found on HDRLib: http://hdrlib.com/
  65914. */
  65915. var HDRCubeTexture = /** @class */ (function (_super) {
  65916. __extends(HDRCubeTexture, _super);
  65917. /**
  65918. * Instantiates an HDRTexture from the following parameters.
  65919. *
  65920. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  65921. * @param scene The scene the texture will be used in
  65922. * @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.
  65923. * @param noMipmap Forces to not generate the mipmap if true
  65924. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  65925. * @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)
  65926. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  65927. */
  65928. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  65929. if (noMipmap === void 0) { noMipmap = false; }
  65930. if (generateHarmonics === void 0) { generateHarmonics = true; }
  65931. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  65932. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  65933. if (onLoad === void 0) { onLoad = null; }
  65934. if (onError === void 0) { onError = null; }
  65935. var _this = _super.call(this, scene) || this;
  65936. _this._useInGammaSpace = false;
  65937. _this._generateHarmonics = true;
  65938. _this._isBABYLONPreprocessed = false;
  65939. _this._onLoad = null;
  65940. _this._onError = null;
  65941. /**
  65942. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  65943. */
  65944. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  65945. /**
  65946. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  65947. * This is usefull at run time to apply the good shader.
  65948. */
  65949. _this.isPMREM = false;
  65950. _this._isBlocking = true;
  65951. if (!url) {
  65952. return _this;
  65953. }
  65954. _this.name = url;
  65955. _this.url = url;
  65956. _this.hasAlpha = false;
  65957. _this.isCube = true;
  65958. _this._textureMatrix = BABYLON.Matrix.Identity();
  65959. _this._onLoad = onLoad;
  65960. _this._onError = onError;
  65961. _this.gammaSpace = false;
  65962. var caps = scene.getEngine().getCaps();
  65963. if (size) {
  65964. _this._isBABYLONPreprocessed = false;
  65965. _this._noMipmap = noMipmap;
  65966. _this._size = size;
  65967. _this._useInGammaSpace = useInGammaSpace;
  65968. _this._usePMREMGenerator = usePMREMGenerator &&
  65969. caps.textureLOD &&
  65970. caps.textureFloat &&
  65971. !_this._useInGammaSpace;
  65972. }
  65973. else {
  65974. _this._isBABYLONPreprocessed = true;
  65975. _this._noMipmap = false;
  65976. _this._useInGammaSpace = false;
  65977. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  65978. !_this._useInGammaSpace;
  65979. }
  65980. _this.isPMREM = _this._usePMREMGenerator;
  65981. _this._texture = _this._getFromCache(url, _this._noMipmap);
  65982. if (!_this._texture) {
  65983. if (!scene.useDelayedTextureLoading) {
  65984. _this.loadTexture();
  65985. }
  65986. else {
  65987. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  65988. }
  65989. }
  65990. return _this;
  65991. }
  65992. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  65993. /**
  65994. * Gets wether or not the texture is blocking during loading.
  65995. */
  65996. get: function () {
  65997. return this._isBlocking;
  65998. },
  65999. /**
  66000. * Sets wether or not the texture is blocking during loading.
  66001. */
  66002. set: function (value) {
  66003. this._isBlocking = value;
  66004. },
  66005. enumerable: true,
  66006. configurable: true
  66007. });
  66008. /**
  66009. * Occurs when the file is a preprocessed .babylon.hdr file.
  66010. */
  66011. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  66012. var _this = this;
  66013. var mipLevels = 0;
  66014. var floatArrayView = null;
  66015. var scene = this.getScene();
  66016. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  66017. var mips = new Array();
  66018. if (!floatArrayView) {
  66019. return mips;
  66020. }
  66021. var startIndex = 30;
  66022. for (var level = 0; level < mipLevels; level++) {
  66023. mips.push([]);
  66024. // Fill each pixel of the mip level.
  66025. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  66026. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  66027. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  66028. mips[level].push(faceData);
  66029. startIndex += faceSize;
  66030. }
  66031. }
  66032. return mips;
  66033. } : null;
  66034. var callback = function (buffer) {
  66035. var scene = _this.getScene();
  66036. if (!scene) {
  66037. return null;
  66038. }
  66039. // Create Native Array Views
  66040. var intArrayView = new Int32Array(buffer);
  66041. floatArrayView = new Float32Array(buffer);
  66042. // Fill header.
  66043. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  66044. _this._size = intArrayView[1]; // CubeMap max mip face size.
  66045. // Update Texture Information.
  66046. if (!_this._texture) {
  66047. return null;
  66048. }
  66049. _this._texture.updateSize(_this._size, _this._size);
  66050. // Fill polynomial information.
  66051. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  66052. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  66053. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  66054. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  66055. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  66056. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  66057. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  66058. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  66059. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  66060. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  66061. _this.sphericalPolynomial = sphericalPolynomial;
  66062. // Fill pixel data.
  66063. mipLevels = intArrayView[29]; // Number of mip levels.
  66064. var startIndex = 30;
  66065. var data = [];
  66066. var faceSize = Math.pow(_this._size, 2) * 3;
  66067. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  66068. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  66069. startIndex += faceSize;
  66070. }
  66071. var results = [];
  66072. var byteArray = null;
  66073. // Push each faces.
  66074. for (var k = 0; k < 6; k++) {
  66075. var dataFace = null;
  66076. // To be deprecated.
  66077. if (version === 1) {
  66078. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  66079. dataFace = data[j];
  66080. }
  66081. // If special cases.
  66082. if (!mipmapGenerator && dataFace) {
  66083. if (!scene.getEngine().getCaps().textureFloat) {
  66084. // 3 channels of 1 bytes per pixel in bytes.
  66085. var byteBuffer = new ArrayBuffer(faceSize);
  66086. byteArray = new Uint8Array(byteBuffer);
  66087. }
  66088. for (var i = 0; i < _this._size * _this._size; i++) {
  66089. // Put in gamma space if requested.
  66090. if (_this._useInGammaSpace) {
  66091. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  66092. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  66093. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  66094. }
  66095. // Convert to int texture for fallback.
  66096. if (byteArray) {
  66097. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  66098. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  66099. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  66100. // May use luminance instead if the result is not accurate.
  66101. var max = Math.max(Math.max(r, g), b);
  66102. if (max > 255) {
  66103. var scale = 255 / max;
  66104. r *= scale;
  66105. g *= scale;
  66106. b *= scale;
  66107. }
  66108. byteArray[(i * 3) + 0] = r;
  66109. byteArray[(i * 3) + 1] = g;
  66110. byteArray[(i * 3) + 2] = b;
  66111. }
  66112. }
  66113. }
  66114. // Fill the array accordingly.
  66115. if (byteArray) {
  66116. results.push(byteArray);
  66117. }
  66118. else {
  66119. results.push(dataFace);
  66120. }
  66121. }
  66122. return results;
  66123. };
  66124. if (scene) {
  66125. 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);
  66126. }
  66127. };
  66128. /**
  66129. * Occurs when the file is raw .hdr file.
  66130. */
  66131. HDRCubeTexture.prototype.loadHDRTexture = function () {
  66132. var _this = this;
  66133. var callback = function (buffer) {
  66134. var scene = _this.getScene();
  66135. if (!scene) {
  66136. return null;
  66137. }
  66138. // Extract the raw linear data.
  66139. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  66140. // Generate harmonics if needed.
  66141. if (_this._generateHarmonics) {
  66142. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  66143. _this.sphericalPolynomial = sphericalPolynomial;
  66144. }
  66145. var results = [];
  66146. var byteArray = null;
  66147. // Push each faces.
  66148. for (var j = 0; j < 6; j++) {
  66149. // Create uintarray fallback.
  66150. if (!scene.getEngine().getCaps().textureFloat) {
  66151. // 3 channels of 1 bytes per pixel in bytes.
  66152. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  66153. byteArray = new Uint8Array(byteBuffer);
  66154. }
  66155. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  66156. // If special cases.
  66157. if (_this._useInGammaSpace || byteArray) {
  66158. for (var i = 0; i < _this._size * _this._size; i++) {
  66159. // Put in gamma space if requested.
  66160. if (_this._useInGammaSpace) {
  66161. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  66162. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  66163. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  66164. }
  66165. // Convert to int texture for fallback.
  66166. if (byteArray) {
  66167. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  66168. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  66169. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  66170. // May use luminance instead if the result is not accurate.
  66171. var max = Math.max(Math.max(r, g), b);
  66172. if (max > 255) {
  66173. var scale = 255 / max;
  66174. r *= scale;
  66175. g *= scale;
  66176. b *= scale;
  66177. }
  66178. byteArray[(i * 3) + 0] = r;
  66179. byteArray[(i * 3) + 1] = g;
  66180. byteArray[(i * 3) + 2] = b;
  66181. }
  66182. }
  66183. }
  66184. if (byteArray) {
  66185. results.push(byteArray);
  66186. }
  66187. else {
  66188. results.push(dataFace);
  66189. }
  66190. }
  66191. return results;
  66192. };
  66193. var mipmapGenerator = null;
  66194. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  66195. // if (!this._noMipmap &&
  66196. // this._usePMREMGenerator) {
  66197. // mipmapGenerator = (data: ArrayBufferView[]) => {
  66198. // // Custom setup of the generator matching with the PBR shader values.
  66199. // var generator = new BABYLON.PMREMGenerator(data,
  66200. // this._size,
  66201. // this._size,
  66202. // 0,
  66203. // 3,
  66204. // this.getScene().getEngine().getCaps().textureFloat,
  66205. // 2048,
  66206. // 0.25,
  66207. // false,
  66208. // true);
  66209. // return generator.filterCubeMap();
  66210. // };
  66211. // }
  66212. var scene = this.getScene();
  66213. if (scene) {
  66214. 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);
  66215. }
  66216. };
  66217. /**
  66218. * Starts the loading process of the texture.
  66219. */
  66220. HDRCubeTexture.prototype.loadTexture = function () {
  66221. if (this._isBABYLONPreprocessed) {
  66222. this.loadBabylonTexture();
  66223. }
  66224. else {
  66225. this.loadHDRTexture();
  66226. }
  66227. };
  66228. HDRCubeTexture.prototype.clone = function () {
  66229. var scene = this.getScene();
  66230. if (!scene) {
  66231. return this;
  66232. }
  66233. var size = (this._isBABYLONPreprocessed ? null : this._size);
  66234. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  66235. // Base texture
  66236. newTexture.level = this.level;
  66237. newTexture.wrapU = this.wrapU;
  66238. newTexture.wrapV = this.wrapV;
  66239. newTexture.coordinatesIndex = this.coordinatesIndex;
  66240. newTexture.coordinatesMode = this.coordinatesMode;
  66241. return newTexture;
  66242. };
  66243. // Methods
  66244. HDRCubeTexture.prototype.delayLoad = function () {
  66245. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  66246. return;
  66247. }
  66248. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  66249. this._texture = this._getFromCache(this.url, this._noMipmap);
  66250. if (!this._texture) {
  66251. this.loadTexture();
  66252. }
  66253. };
  66254. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  66255. return this._textureMatrix;
  66256. };
  66257. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  66258. this._textureMatrix = value;
  66259. };
  66260. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  66261. var texture = null;
  66262. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  66263. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  66264. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  66265. texture.name = parsedTexture.name;
  66266. texture.hasAlpha = parsedTexture.hasAlpha;
  66267. texture.level = parsedTexture.level;
  66268. texture.coordinatesMode = parsedTexture.coordinatesMode;
  66269. texture.isBlocking = parsedTexture.isBlocking;
  66270. }
  66271. return texture;
  66272. };
  66273. HDRCubeTexture.prototype.serialize = function () {
  66274. if (!this.name) {
  66275. return null;
  66276. }
  66277. var serializationObject = {};
  66278. serializationObject.name = this.name;
  66279. serializationObject.hasAlpha = this.hasAlpha;
  66280. serializationObject.isCube = true;
  66281. serializationObject.level = this.level;
  66282. serializationObject.size = this._size;
  66283. serializationObject.coordinatesMode = this.coordinatesMode;
  66284. serializationObject.useInGammaSpace = this._useInGammaSpace;
  66285. serializationObject.generateHarmonics = this._generateHarmonics;
  66286. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  66287. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  66288. serializationObject.customType = "BABYLON.HDRCubeTexture";
  66289. serializationObject.noMipmap = this._noMipmap;
  66290. serializationObject.isBlocking = this._isBlocking;
  66291. return serializationObject;
  66292. };
  66293. /**
  66294. * Saves as a file the data contained in the texture in a binary format.
  66295. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  66296. * as the spherical used in the lighting.
  66297. * @param url The HDR file url.
  66298. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  66299. * @param onError Method called if any error happens during download.
  66300. * @return The packed binary data.
  66301. */
  66302. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  66303. if (onError === void 0) { onError = null; }
  66304. var callback = function (buffer) {
  66305. var data = new Blob([buffer], { type: 'application/octet-stream' });
  66306. // Returns a URL you can use as a href.
  66307. var objUrl = window.URL.createObjectURL(data);
  66308. // Simulates a link to it and click to dowload.
  66309. var a = document.createElement("a");
  66310. document.body.appendChild(a);
  66311. a.style.display = "none";
  66312. a.href = objUrl;
  66313. a.download = "envmap.babylon.hdr";
  66314. a.click();
  66315. };
  66316. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  66317. };
  66318. /**
  66319. * Serializes the data contained in the texture in a binary format.
  66320. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  66321. * as the spherical used in the lighting.
  66322. * @param url The HDR file url.
  66323. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  66324. * @param onError Method called if any error happens during download.
  66325. * @return The packed binary data.
  66326. */
  66327. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  66328. if (onError === void 0) { onError = null; }
  66329. // Needs the url tho create the texture.
  66330. if (!url) {
  66331. return;
  66332. }
  66333. // Check Power of two size.
  66334. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  66335. return;
  66336. }
  66337. // Coming Back in 3.x.
  66338. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  66339. };
  66340. HDRCubeTexture._facesMapping = [
  66341. "right",
  66342. "left",
  66343. "up",
  66344. "down",
  66345. "front",
  66346. "back"
  66347. ];
  66348. return HDRCubeTexture;
  66349. }(BABYLON.BaseTexture));
  66350. BABYLON.HDRCubeTexture = HDRCubeTexture;
  66351. })(BABYLON || (BABYLON = {}));
  66352. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  66353. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  66354. // Huge respect for a such great lib.
  66355. // Earcut license:
  66356. // Copyright (c) 2016, Mapbox
  66357. //
  66358. // Permission to use, copy, modify, and/or distribute this software for any purpose
  66359. // with or without fee is hereby granted, provided that the above copyright notice
  66360. // and this permission notice appear in all copies.
  66361. //
  66362. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  66363. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  66364. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  66365. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  66366. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  66367. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  66368. // THIS SOFTWARE.
  66369. var Earcut;
  66370. (function (Earcut) {
  66371. /**
  66372. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  66373. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  66374. * @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).
  66375. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  66376. */
  66377. function earcut(data, holeIndices, dim) {
  66378. dim = dim || 2;
  66379. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  66380. if (!outerNode)
  66381. return triangles;
  66382. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  66383. if (hasHoles)
  66384. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  66385. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  66386. if (data.length > 80 * dim) {
  66387. minX = maxX = data[0];
  66388. minY = maxY = data[1];
  66389. for (var i = dim; i < outerLen; i += dim) {
  66390. x = data[i];
  66391. y = data[i + 1];
  66392. if (x < minX)
  66393. minX = x;
  66394. if (y < minY)
  66395. minY = y;
  66396. if (x > maxX)
  66397. maxX = x;
  66398. if (y > maxY)
  66399. maxY = y;
  66400. }
  66401. // minX, minY and size are later used to transform coords into integers for z-order calculation
  66402. size = Math.max(maxX - minX, maxY - minY);
  66403. }
  66404. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  66405. return triangles;
  66406. }
  66407. Earcut.earcut = earcut;
  66408. var Node = /** @class */ (function () {
  66409. function Node(i, x, y) {
  66410. this.i = i;
  66411. this.x = x;
  66412. this.y = y;
  66413. this.prev = null;
  66414. this.next = null;
  66415. this.z = null;
  66416. this.prevZ = null;
  66417. this.nextZ = null;
  66418. this.steiner = false;
  66419. }
  66420. return Node;
  66421. }());
  66422. // create a circular doubly linked list from polygon points in the specified winding order
  66423. function linkedList(data, start, end, dim, clockwise) {
  66424. var i, last = null;
  66425. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  66426. for (i = start; i < end; i += dim)
  66427. last = insertNode(i, data[i], data[i + 1], last);
  66428. }
  66429. else {
  66430. for (i = end - dim; i >= start; i -= dim)
  66431. last = insertNode(i, data[i], data[i + 1], last);
  66432. }
  66433. if (last && equals(last, last.next)) {
  66434. removeNode(last);
  66435. last = last.next;
  66436. }
  66437. return last;
  66438. }
  66439. // eliminate colinear or duplicate points
  66440. function filterPoints(start, end) {
  66441. if (!start)
  66442. return start;
  66443. if (!end)
  66444. end = start;
  66445. var p = start, again;
  66446. do {
  66447. again = false;
  66448. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  66449. removeNode(p);
  66450. p = end = p.prev;
  66451. if (p === p.next)
  66452. return undefined;
  66453. again = true;
  66454. }
  66455. else {
  66456. p = p.next;
  66457. }
  66458. } while (again || p !== end);
  66459. return end;
  66460. }
  66461. // main ear slicing loop which triangulates a polygon (given as a linked list)
  66462. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  66463. if (!ear)
  66464. return;
  66465. // interlink polygon nodes in z-order
  66466. if (!pass && size)
  66467. indexCurve(ear, minX, minY, size);
  66468. var stop = ear, prev, next;
  66469. // iterate through ears, slicing them one by one
  66470. while (ear.prev !== ear.next) {
  66471. prev = ear.prev;
  66472. next = ear.next;
  66473. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  66474. // cut off the triangle
  66475. triangles.push(prev.i / dim);
  66476. triangles.push(ear.i / dim);
  66477. triangles.push(next.i / dim);
  66478. removeNode(ear);
  66479. // skipping the next vertice leads to less sliver triangles
  66480. ear = next.next;
  66481. stop = next.next;
  66482. continue;
  66483. }
  66484. ear = next;
  66485. // if we looped through the whole remaining polygon and can't find any more ears
  66486. if (ear === stop) {
  66487. // try filtering points and slicing again
  66488. if (!pass) {
  66489. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  66490. // if this didn't work, try curing all small self-intersections locally
  66491. }
  66492. else if (pass === 1) {
  66493. ear = cureLocalIntersections(ear, triangles, dim);
  66494. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  66495. // as a last resort, try splitting the remaining polygon into two
  66496. }
  66497. else if (pass === 2) {
  66498. splitEarcut(ear, triangles, dim, minX, minY, size);
  66499. }
  66500. break;
  66501. }
  66502. }
  66503. }
  66504. // check whether a polygon node forms a valid ear with adjacent nodes
  66505. function isEar(ear) {
  66506. var a = ear.prev, b = ear, c = ear.next;
  66507. if (area(a, b, c) >= 0)
  66508. return false; // reflex, can't be an ear
  66509. // now make sure we don't have other points inside the potential ear
  66510. var p = ear.next.next;
  66511. while (p !== ear.prev) {
  66512. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66513. area(p.prev, p, p.next) >= 0)
  66514. return false;
  66515. p = p.next;
  66516. }
  66517. return true;
  66518. }
  66519. function isEarHashed(ear, minX, minY, size) {
  66520. var a = ear.prev, b = ear, c = ear.next;
  66521. if (area(a, b, c) >= 0)
  66522. return false; // reflex, can't be an ear
  66523. // triangle bbox; min & max are calculated like this for speed
  66524. 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);
  66525. // z-order range for the current triangle bbox;
  66526. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  66527. // first look for points inside the triangle in increasing z-order
  66528. var p = ear.nextZ;
  66529. while (p && p.z <= maxZ) {
  66530. if (p !== ear.prev &&
  66531. p !== ear.next &&
  66532. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66533. area(p.prev, p, p.next) >= 0)
  66534. return false;
  66535. p = p.nextZ;
  66536. }
  66537. // then look for points in decreasing z-order
  66538. p = ear.prevZ;
  66539. while (p && p.z >= minZ) {
  66540. if (p !== ear.prev &&
  66541. p !== ear.next &&
  66542. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66543. area(p.prev, p, p.next) >= 0)
  66544. return false;
  66545. p = p.prevZ;
  66546. }
  66547. return true;
  66548. }
  66549. // go through all polygon nodes and cure small local self-intersections
  66550. function cureLocalIntersections(start, triangles, dim) {
  66551. var p = start;
  66552. do {
  66553. var a = p.prev, b = p.next.next;
  66554. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  66555. triangles.push(a.i / dim);
  66556. triangles.push(p.i / dim);
  66557. triangles.push(b.i / dim);
  66558. // remove two nodes involved
  66559. removeNode(p);
  66560. removeNode(p.next);
  66561. p = start = b;
  66562. }
  66563. p = p.next;
  66564. } while (p !== start);
  66565. return p;
  66566. }
  66567. // try splitting polygon into two and triangulate them independently
  66568. function splitEarcut(start, triangles, dim, minX, minY, size) {
  66569. // look for a valid diagonal that divides the polygon into two
  66570. var a = start;
  66571. do {
  66572. var b = a.next.next;
  66573. while (b !== a.prev) {
  66574. if (a.i !== b.i && isValidDiagonal(a, b)) {
  66575. // split the polygon in two by the diagonal
  66576. var c = splitPolygon(a, b);
  66577. // filter colinear points around the cuts
  66578. a = filterPoints(a, a.next);
  66579. c = filterPoints(c, c.next);
  66580. // run earcut on each half
  66581. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  66582. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  66583. return;
  66584. }
  66585. b = b.next;
  66586. }
  66587. a = a.next;
  66588. } while (a !== start);
  66589. }
  66590. // link every hole into the outer loop, producing a single-ring polygon without holes
  66591. function eliminateHoles(data, holeIndices, outerNode, dim) {
  66592. var queue = [], i, len, start, end, list;
  66593. for (i = 0, len = holeIndices.length; i < len; i++) {
  66594. start = holeIndices[i] * dim;
  66595. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66596. list = linkedList(data, start, end, dim, false);
  66597. if (list === list.next)
  66598. list.steiner = true;
  66599. queue.push(getLeftmost(list));
  66600. }
  66601. queue.sort(compareX);
  66602. // process holes from left to right
  66603. for (i = 0; i < queue.length; i++) {
  66604. eliminateHole(queue[i], outerNode);
  66605. outerNode = filterPoints(outerNode, outerNode.next);
  66606. }
  66607. return outerNode;
  66608. }
  66609. function compareX(a, b) {
  66610. return a.x - b.x;
  66611. }
  66612. // find a bridge between vertices that connects hole with an outer ring and and link it
  66613. function eliminateHole(hole, outerNode) {
  66614. outerNode = findHoleBridge(hole, outerNode);
  66615. if (outerNode) {
  66616. var b = splitPolygon(outerNode, hole);
  66617. filterPoints(b, b.next);
  66618. }
  66619. }
  66620. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  66621. function findHoleBridge(hole, outerNode) {
  66622. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  66623. // find a segment intersected by a ray from the hole's leftmost point to the left;
  66624. // segment's endpoint with lesser x will be potential connection point
  66625. do {
  66626. if (hy <= p.y && hy >= p.next.y) {
  66627. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  66628. if (x <= hx && x > qx) {
  66629. qx = x;
  66630. if (x === hx) {
  66631. if (hy === p.y)
  66632. return p;
  66633. if (hy === p.next.y)
  66634. return p.next;
  66635. }
  66636. m = p.x < p.next.x ? p : p.next;
  66637. }
  66638. }
  66639. p = p.next;
  66640. } while (p !== outerNode);
  66641. if (!m)
  66642. return null;
  66643. if (hx === qx)
  66644. return m.prev; // hole touches outer segment; pick lower endpoint
  66645. // look for points inside the triangle of hole point, segment intersection and endpoint;
  66646. // if there are no points found, we have a valid connection;
  66647. // otherwise choose the point of the minimum angle with the ray as connection point
  66648. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  66649. p = m.next;
  66650. while (p !== stop) {
  66651. if (hx >= p.x &&
  66652. p.x >= mx &&
  66653. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  66654. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  66655. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  66656. m = p;
  66657. tanMin = tan;
  66658. }
  66659. }
  66660. p = p.next;
  66661. }
  66662. return m;
  66663. }
  66664. // interlink polygon nodes in z-order
  66665. function indexCurve(start, minX, minY, size) {
  66666. var p = start;
  66667. do {
  66668. if (p.z === null)
  66669. p.z = zOrder(p.x, p.y, minX, minY, size);
  66670. p.prevZ = p.prev;
  66671. p.nextZ = p.next;
  66672. p = p.next;
  66673. } while (p !== start);
  66674. p.prevZ.nextZ = null;
  66675. p.prevZ = null;
  66676. sortLinked(p);
  66677. }
  66678. // Simon Tatham's linked list merge sort algorithm
  66679. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  66680. function sortLinked(list) {
  66681. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  66682. do {
  66683. p = list;
  66684. list = null;
  66685. tail = null;
  66686. numMerges = 0;
  66687. while (p) {
  66688. numMerges++;
  66689. q = p;
  66690. pSize = 0;
  66691. for (i = 0; i < inSize; i++) {
  66692. pSize++;
  66693. q = q.nextZ;
  66694. if (!q)
  66695. break;
  66696. }
  66697. qSize = inSize;
  66698. while (pSize > 0 || (qSize > 0 && q)) {
  66699. if (pSize === 0) {
  66700. e = q;
  66701. q = q.nextZ;
  66702. qSize--;
  66703. }
  66704. else if (qSize === 0 || !q) {
  66705. e = p;
  66706. p = p.nextZ;
  66707. pSize--;
  66708. }
  66709. else if (p.z <= q.z) {
  66710. e = p;
  66711. p = p.nextZ;
  66712. pSize--;
  66713. }
  66714. else {
  66715. e = q;
  66716. q = q.nextZ;
  66717. qSize--;
  66718. }
  66719. if (tail)
  66720. tail.nextZ = e;
  66721. else
  66722. list = e;
  66723. e.prevZ = tail;
  66724. tail = e;
  66725. }
  66726. p = q;
  66727. }
  66728. tail.nextZ = null;
  66729. inSize *= 2;
  66730. } while (numMerges > 1);
  66731. return list;
  66732. }
  66733. // z-order of a point given coords and size of the data bounding box
  66734. function zOrder(x, y, minX, minY, size) {
  66735. // coords are transformed into non-negative 15-bit integer range
  66736. x = 32767 * (x - minX) / size;
  66737. y = 32767 * (y - minY) / size;
  66738. x = (x | (x << 8)) & 0x00FF00FF;
  66739. x = (x | (x << 4)) & 0x0F0F0F0F;
  66740. x = (x | (x << 2)) & 0x33333333;
  66741. x = (x | (x << 1)) & 0x55555555;
  66742. y = (y | (y << 8)) & 0x00FF00FF;
  66743. y = (y | (y << 4)) & 0x0F0F0F0F;
  66744. y = (y | (y << 2)) & 0x33333333;
  66745. y = (y | (y << 1)) & 0x55555555;
  66746. return x | (y << 1);
  66747. }
  66748. // find the leftmost node of a polygon ring
  66749. function getLeftmost(start) {
  66750. var p = start, leftmost = start;
  66751. do {
  66752. if (p.x < leftmost.x)
  66753. leftmost = p;
  66754. p = p.next;
  66755. } while (p !== start);
  66756. return leftmost;
  66757. }
  66758. // check if a point lies within a convex triangle
  66759. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  66760. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  66761. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  66762. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  66763. }
  66764. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  66765. function isValidDiagonal(a, b) {
  66766. return a.next.i !== b.i &&
  66767. a.prev.i !== b.i &&
  66768. !intersectsPolygon(a, b) &&
  66769. locallyInside(a, b) &&
  66770. locallyInside(b, a) &&
  66771. middleInside(a, b);
  66772. }
  66773. // signed area of a triangle
  66774. function area(p, q, r) {
  66775. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  66776. }
  66777. // check if two points are equal
  66778. function equals(p1, p2) {
  66779. return p1.x === p2.x && p1.y === p2.y;
  66780. }
  66781. // check if two segments intersect
  66782. function intersects(p1, q1, p2, q2) {
  66783. if ((equals(p1, q1) && equals(p2, q2)) ||
  66784. (equals(p1, q2) && equals(p2, q1)))
  66785. return true;
  66786. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  66787. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  66788. }
  66789. // check if a polygon diagonal intersects any polygon segments
  66790. function intersectsPolygon(a, b) {
  66791. var p = a;
  66792. do {
  66793. if (p.i !== a.i &&
  66794. p.next.i !== a.i &&
  66795. p.i !== b.i &&
  66796. p.next.i !== b.i &&
  66797. intersects(p, p.next, a, b))
  66798. return true;
  66799. p = p.next;
  66800. } while (p !== a);
  66801. return false;
  66802. }
  66803. // check if a polygon diagonal is locally inside the polygon
  66804. function locallyInside(a, b) {
  66805. return area(a.prev, a, a.next) < 0
  66806. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  66807. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  66808. }
  66809. // check if the middle point of a polygon diagonal is inside the polygon
  66810. function middleInside(a, b) {
  66811. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  66812. do {
  66813. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  66814. inside = !inside;
  66815. p = p.next;
  66816. } while (p !== a);
  66817. return inside;
  66818. }
  66819. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  66820. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  66821. function splitPolygon(a, b) {
  66822. 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;
  66823. a.next = b;
  66824. b.prev = a;
  66825. a2.next = an;
  66826. an.prev = a2;
  66827. b2.next = a2;
  66828. a2.prev = b2;
  66829. bp.next = b2;
  66830. b2.prev = bp;
  66831. return b2;
  66832. }
  66833. // create a node and optionally link it with previous one (in a circular doubly linked list)
  66834. function insertNode(i, x, y, last) {
  66835. var p = new Node(i, x, y);
  66836. if (!last) {
  66837. p.prev = p;
  66838. p.next = p;
  66839. }
  66840. else {
  66841. p.next = last.next;
  66842. p.prev = last;
  66843. last.next.prev = p;
  66844. last.next = p;
  66845. }
  66846. return p;
  66847. }
  66848. function removeNode(p) {
  66849. p.next.prev = p.prev;
  66850. p.prev.next = p.next;
  66851. if (p.prevZ)
  66852. p.prevZ.nextZ = p.nextZ;
  66853. if (p.nextZ)
  66854. p.nextZ.prevZ = p.prevZ;
  66855. }
  66856. /**
  66857. * return a percentage difference between the polygon area and its triangulation area;
  66858. * used to verify correctness of triangulation
  66859. */
  66860. function deviation(data, holeIndices, dim, triangles) {
  66861. var hasHoles = holeIndices && holeIndices.length;
  66862. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  66863. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  66864. if (hasHoles) {
  66865. for (var i = 0, len = holeIndices.length; i < len; i++) {
  66866. var start = holeIndices[i] * dim;
  66867. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66868. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  66869. }
  66870. }
  66871. var trianglesArea = 0;
  66872. for (i = 0; i < triangles.length; i += 3) {
  66873. var a = triangles[i] * dim;
  66874. var b = triangles[i + 1] * dim;
  66875. var c = triangles[i + 2] * dim;
  66876. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  66877. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  66878. }
  66879. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  66880. }
  66881. Earcut.deviation = deviation;
  66882. ;
  66883. function signedArea(data, start, end, dim) {
  66884. var sum = 0;
  66885. for (var i = start, j = end - dim; i < end; i += dim) {
  66886. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  66887. j = i;
  66888. }
  66889. return sum;
  66890. }
  66891. /**
  66892. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  66893. */
  66894. function flatten(data) {
  66895. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  66896. for (var i = 0; i < data.length; i++) {
  66897. for (var j = 0; j < data[i].length; j++) {
  66898. for (var d = 0; d < dim; d++)
  66899. result.vertices.push(data[i][j][d]);
  66900. }
  66901. if (i > 0) {
  66902. holeIndex += data[i - 1].length;
  66903. result.holes.push(holeIndex);
  66904. }
  66905. }
  66906. return result;
  66907. }
  66908. Earcut.flatten = flatten;
  66909. ;
  66910. })(Earcut || (Earcut = {}));
  66911. //# sourceMappingURL=babylon.earcut.js.map
  66912. var BABYLON;
  66913. (function (BABYLON) {
  66914. var IndexedVector2 = /** @class */ (function (_super) {
  66915. __extends(IndexedVector2, _super);
  66916. function IndexedVector2(original, index) {
  66917. var _this = _super.call(this, original.x, original.y) || this;
  66918. _this.index = index;
  66919. return _this;
  66920. }
  66921. return IndexedVector2;
  66922. }(BABYLON.Vector2));
  66923. var PolygonPoints = /** @class */ (function () {
  66924. function PolygonPoints() {
  66925. this.elements = new Array();
  66926. }
  66927. PolygonPoints.prototype.add = function (originalPoints) {
  66928. var _this = this;
  66929. var result = new Array();
  66930. originalPoints.forEach(function (point) {
  66931. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  66932. var newPoint = new IndexedVector2(point, _this.elements.length);
  66933. result.push(newPoint);
  66934. _this.elements.push(newPoint);
  66935. }
  66936. });
  66937. return result;
  66938. };
  66939. PolygonPoints.prototype.computeBounds = function () {
  66940. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66941. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66942. this.elements.forEach(function (point) {
  66943. // x
  66944. if (point.x < lmin.x) {
  66945. lmin.x = point.x;
  66946. }
  66947. else if (point.x > lmax.x) {
  66948. lmax.x = point.x;
  66949. }
  66950. // y
  66951. if (point.y < lmin.y) {
  66952. lmin.y = point.y;
  66953. }
  66954. else if (point.y > lmax.y) {
  66955. lmax.y = point.y;
  66956. }
  66957. });
  66958. return {
  66959. min: lmin,
  66960. max: lmax,
  66961. width: lmax.x - lmin.x,
  66962. height: lmax.y - lmin.y
  66963. };
  66964. };
  66965. return PolygonPoints;
  66966. }());
  66967. var Polygon = /** @class */ (function () {
  66968. function Polygon() {
  66969. }
  66970. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  66971. return [
  66972. new BABYLON.Vector2(xmin, ymin),
  66973. new BABYLON.Vector2(xmax, ymin),
  66974. new BABYLON.Vector2(xmax, ymax),
  66975. new BABYLON.Vector2(xmin, ymax)
  66976. ];
  66977. };
  66978. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  66979. if (cx === void 0) { cx = 0; }
  66980. if (cy === void 0) { cy = 0; }
  66981. if (numberOfSides === void 0) { numberOfSides = 32; }
  66982. var result = new Array();
  66983. var angle = 0;
  66984. var increment = (Math.PI * 2) / numberOfSides;
  66985. for (var i = 0; i < numberOfSides; i++) {
  66986. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  66987. angle -= increment;
  66988. }
  66989. return result;
  66990. };
  66991. Polygon.Parse = function (input) {
  66992. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  66993. var i, result = [];
  66994. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  66995. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  66996. }
  66997. return result;
  66998. };
  66999. Polygon.StartingAt = function (x, y) {
  67000. return BABYLON.Path2.StartingAt(x, y);
  67001. };
  67002. return Polygon;
  67003. }());
  67004. BABYLON.Polygon = Polygon;
  67005. var PolygonMeshBuilder = /** @class */ (function () {
  67006. function PolygonMeshBuilder(name, contours, scene) {
  67007. this._points = new PolygonPoints();
  67008. this._outlinepoints = new PolygonPoints();
  67009. this._holes = new Array();
  67010. this._epoints = new Array();
  67011. this._eholes = new Array();
  67012. this._name = name;
  67013. this._scene = scene;
  67014. var points;
  67015. if (contours instanceof BABYLON.Path2) {
  67016. points = contours.getPoints();
  67017. }
  67018. else {
  67019. points = contours;
  67020. }
  67021. this._addToepoint(points);
  67022. this._points.add(points);
  67023. this._outlinepoints.add(points);
  67024. }
  67025. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  67026. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  67027. var p = points_1[_i];
  67028. this._epoints.push(p.x, p.y);
  67029. }
  67030. };
  67031. PolygonMeshBuilder.prototype.addHole = function (hole) {
  67032. this._points.add(hole);
  67033. var holepoints = new PolygonPoints();
  67034. holepoints.add(hole);
  67035. this._holes.push(holepoints);
  67036. this._eholes.push(this._epoints.length / 2);
  67037. this._addToepoint(hole);
  67038. return this;
  67039. };
  67040. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  67041. var _this = this;
  67042. if (updatable === void 0) { updatable = false; }
  67043. if (depth === void 0) { depth = 0; }
  67044. var result = new BABYLON.Mesh(this._name, this._scene);
  67045. var normals = new Array();
  67046. var positions = new Array();
  67047. var uvs = new Array();
  67048. var bounds = this._points.computeBounds();
  67049. this._points.elements.forEach(function (p) {
  67050. normals.push(0, 1.0, 0);
  67051. positions.push(p.x, 0, p.y);
  67052. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  67053. });
  67054. var indices = new Array();
  67055. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  67056. for (var i = 0; i < res.length; i++) {
  67057. indices.push(res[i]);
  67058. }
  67059. if (depth > 0) {
  67060. var positionscount = (positions.length / 3); //get the current pointcount
  67061. this._points.elements.forEach(function (p) {
  67062. normals.push(0, -1.0, 0);
  67063. positions.push(p.x, -depth, p.y);
  67064. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  67065. });
  67066. var totalCount = indices.length;
  67067. for (var i = 0; i < totalCount; i += 3) {
  67068. var i0 = indices[i + 0];
  67069. var i1 = indices[i + 1];
  67070. var i2 = indices[i + 2];
  67071. indices.push(i2 + positionscount);
  67072. indices.push(i1 + positionscount);
  67073. indices.push(i0 + positionscount);
  67074. }
  67075. //Add the sides
  67076. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  67077. this._holes.forEach(function (hole) {
  67078. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  67079. });
  67080. }
  67081. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  67082. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  67083. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  67084. result.setIndices(indices);
  67085. return result;
  67086. };
  67087. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  67088. var StartIndex = positions.length / 3;
  67089. var ulength = 0;
  67090. for (var i = 0; i < points.elements.length; i++) {
  67091. var p = points.elements[i];
  67092. var p1;
  67093. if ((i + 1) > points.elements.length - 1) {
  67094. p1 = points.elements[0];
  67095. }
  67096. else {
  67097. p1 = points.elements[i + 1];
  67098. }
  67099. positions.push(p.x, 0, p.y);
  67100. positions.push(p.x, -depth, p.y);
  67101. positions.push(p1.x, 0, p1.y);
  67102. positions.push(p1.x, -depth, p1.y);
  67103. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  67104. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  67105. var v3 = v2.subtract(v1);
  67106. var v4 = new BABYLON.Vector3(0, 1, 0);
  67107. var vn = BABYLON.Vector3.Cross(v3, v4);
  67108. vn = vn.normalize();
  67109. uvs.push(ulength / bounds.width, 0);
  67110. uvs.push(ulength / bounds.width, 1);
  67111. ulength += v3.length();
  67112. uvs.push((ulength / bounds.width), 0);
  67113. uvs.push((ulength / bounds.width), 1);
  67114. if (!flip) {
  67115. normals.push(-vn.x, -vn.y, -vn.z);
  67116. normals.push(-vn.x, -vn.y, -vn.z);
  67117. normals.push(-vn.x, -vn.y, -vn.z);
  67118. normals.push(-vn.x, -vn.y, -vn.z);
  67119. indices.push(StartIndex);
  67120. indices.push(StartIndex + 1);
  67121. indices.push(StartIndex + 2);
  67122. indices.push(StartIndex + 1);
  67123. indices.push(StartIndex + 3);
  67124. indices.push(StartIndex + 2);
  67125. }
  67126. else {
  67127. normals.push(vn.x, vn.y, vn.z);
  67128. normals.push(vn.x, vn.y, vn.z);
  67129. normals.push(vn.x, vn.y, vn.z);
  67130. normals.push(vn.x, vn.y, vn.z);
  67131. indices.push(StartIndex);
  67132. indices.push(StartIndex + 2);
  67133. indices.push(StartIndex + 1);
  67134. indices.push(StartIndex + 1);
  67135. indices.push(StartIndex + 2);
  67136. indices.push(StartIndex + 3);
  67137. }
  67138. StartIndex += 4;
  67139. }
  67140. ;
  67141. };
  67142. return PolygonMeshBuilder;
  67143. }());
  67144. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  67145. })(BABYLON || (BABYLON = {}));
  67146. //# sourceMappingURL=babylon.polygonMesh.js.map
  67147. var BABYLON;
  67148. (function (BABYLON) {
  67149. // Unique ID when we import meshes from Babylon to CSG
  67150. var currentCSGMeshId = 0;
  67151. // # class Vertex
  67152. // Represents a vertex of a polygon. Use your own vertex class instead of this
  67153. // one to provide additional features like texture coordinates and vertex
  67154. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  67155. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  67156. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  67157. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  67158. // is not used anywhere else.
  67159. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  67160. var Vertex = /** @class */ (function () {
  67161. function Vertex(pos, normal, uv) {
  67162. this.pos = pos;
  67163. this.normal = normal;
  67164. this.uv = uv;
  67165. }
  67166. Vertex.prototype.clone = function () {
  67167. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  67168. };
  67169. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  67170. // orientation of a polygon is flipped.
  67171. Vertex.prototype.flip = function () {
  67172. this.normal = this.normal.scale(-1);
  67173. };
  67174. // Create a new vertex between this vertex and `other` by linearly
  67175. // interpolating all properties using a parameter of `t`. Subclasses should
  67176. // override this to interpolate additional properties.
  67177. Vertex.prototype.interpolate = function (other, t) {
  67178. 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));
  67179. };
  67180. return Vertex;
  67181. }());
  67182. // # class Plane
  67183. // Represents a plane in 3D space.
  67184. var Plane = /** @class */ (function () {
  67185. function Plane(normal, w) {
  67186. this.normal = normal;
  67187. this.w = w;
  67188. }
  67189. Plane.FromPoints = function (a, b, c) {
  67190. var v0 = c.subtract(a);
  67191. var v1 = b.subtract(a);
  67192. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  67193. return null;
  67194. }
  67195. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  67196. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  67197. };
  67198. Plane.prototype.clone = function () {
  67199. return new Plane(this.normal.clone(), this.w);
  67200. };
  67201. Plane.prototype.flip = function () {
  67202. this.normal.scaleInPlace(-1);
  67203. this.w = -this.w;
  67204. };
  67205. // Split `polygon` by this plane if needed, then put the polygon or polygon
  67206. // fragments in the appropriate lists. Coplanar polygons go into either
  67207. // `coplanarFront` or `coplanarBack` depending on their orientation with
  67208. // respect to this plane. Polygons in front or in back of this plane go into
  67209. // either `front` or `back`.
  67210. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  67211. var COPLANAR = 0;
  67212. var FRONT = 1;
  67213. var BACK = 2;
  67214. var SPANNING = 3;
  67215. // Classify each point as well as the entire polygon into one of the above
  67216. // four classes.
  67217. var polygonType = 0;
  67218. var types = [];
  67219. var i;
  67220. var t;
  67221. for (i = 0; i < polygon.vertices.length; i++) {
  67222. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  67223. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  67224. polygonType |= type;
  67225. types.push(type);
  67226. }
  67227. // Put the polygon in the correct list, splitting it when necessary.
  67228. switch (polygonType) {
  67229. case COPLANAR:
  67230. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  67231. break;
  67232. case FRONT:
  67233. front.push(polygon);
  67234. break;
  67235. case BACK:
  67236. back.push(polygon);
  67237. break;
  67238. case SPANNING:
  67239. var f = [], b = [];
  67240. for (i = 0; i < polygon.vertices.length; i++) {
  67241. var j = (i + 1) % polygon.vertices.length;
  67242. var ti = types[i], tj = types[j];
  67243. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  67244. if (ti !== BACK)
  67245. f.push(vi);
  67246. if (ti !== FRONT)
  67247. b.push(ti !== BACK ? vi.clone() : vi);
  67248. if ((ti | tj) === SPANNING) {
  67249. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  67250. var v = vi.interpolate(vj, t);
  67251. f.push(v);
  67252. b.push(v.clone());
  67253. }
  67254. }
  67255. var poly;
  67256. if (f.length >= 3) {
  67257. poly = new Polygon(f, polygon.shared);
  67258. if (poly.plane)
  67259. front.push(poly);
  67260. }
  67261. if (b.length >= 3) {
  67262. poly = new Polygon(b, polygon.shared);
  67263. if (poly.plane)
  67264. back.push(poly);
  67265. }
  67266. break;
  67267. }
  67268. };
  67269. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  67270. // point is on the plane.
  67271. Plane.EPSILON = 1e-5;
  67272. return Plane;
  67273. }());
  67274. // # class Polygon
  67275. // Represents a convex polygon. The vertices used to initialize a polygon must
  67276. // be coplanar and form a convex loop.
  67277. //
  67278. // Each convex polygon has a `shared` property, which is shared between all
  67279. // polygons that are clones of each other or were split from the same polygon.
  67280. // This can be used to define per-polygon properties (such as surface color).
  67281. var Polygon = /** @class */ (function () {
  67282. function Polygon(vertices, shared) {
  67283. this.vertices = vertices;
  67284. this.shared = shared;
  67285. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  67286. }
  67287. Polygon.prototype.clone = function () {
  67288. var vertices = this.vertices.map(function (v) { return v.clone(); });
  67289. return new Polygon(vertices, this.shared);
  67290. };
  67291. Polygon.prototype.flip = function () {
  67292. this.vertices.reverse().map(function (v) { v.flip(); });
  67293. this.plane.flip();
  67294. };
  67295. return Polygon;
  67296. }());
  67297. // # class Node
  67298. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  67299. // by picking a polygon to split along. That polygon (and all other coplanar
  67300. // polygons) are added directly to that node and the other polygons are added to
  67301. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  67302. // no distinction between internal and leaf nodes.
  67303. var Node = /** @class */ (function () {
  67304. function Node(polygons) {
  67305. this.plane = null;
  67306. this.front = null;
  67307. this.back = null;
  67308. this.polygons = new Array();
  67309. if (polygons) {
  67310. this.build(polygons);
  67311. }
  67312. }
  67313. Node.prototype.clone = function () {
  67314. var node = new Node();
  67315. node.plane = this.plane && this.plane.clone();
  67316. node.front = this.front && this.front.clone();
  67317. node.back = this.back && this.back.clone();
  67318. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  67319. return node;
  67320. };
  67321. // Convert solid space to empty space and empty space to solid space.
  67322. Node.prototype.invert = function () {
  67323. for (var i = 0; i < this.polygons.length; i++) {
  67324. this.polygons[i].flip();
  67325. }
  67326. if (this.plane) {
  67327. this.plane.flip();
  67328. }
  67329. if (this.front) {
  67330. this.front.invert();
  67331. }
  67332. if (this.back) {
  67333. this.back.invert();
  67334. }
  67335. var temp = this.front;
  67336. this.front = this.back;
  67337. this.back = temp;
  67338. };
  67339. // Recursively remove all polygons in `polygons` that are inside this BSP
  67340. // tree.
  67341. Node.prototype.clipPolygons = function (polygons) {
  67342. if (!this.plane)
  67343. return polygons.slice();
  67344. var front = new Array(), back = new Array();
  67345. for (var i = 0; i < polygons.length; i++) {
  67346. this.plane.splitPolygon(polygons[i], front, back, front, back);
  67347. }
  67348. if (this.front) {
  67349. front = this.front.clipPolygons(front);
  67350. }
  67351. if (this.back) {
  67352. back = this.back.clipPolygons(back);
  67353. }
  67354. else {
  67355. back = [];
  67356. }
  67357. return front.concat(back);
  67358. };
  67359. // Remove all polygons in this BSP tree that are inside the other BSP tree
  67360. // `bsp`.
  67361. Node.prototype.clipTo = function (bsp) {
  67362. this.polygons = bsp.clipPolygons(this.polygons);
  67363. if (this.front)
  67364. this.front.clipTo(bsp);
  67365. if (this.back)
  67366. this.back.clipTo(bsp);
  67367. };
  67368. // Return a list of all polygons in this BSP tree.
  67369. Node.prototype.allPolygons = function () {
  67370. var polygons = this.polygons.slice();
  67371. if (this.front)
  67372. polygons = polygons.concat(this.front.allPolygons());
  67373. if (this.back)
  67374. polygons = polygons.concat(this.back.allPolygons());
  67375. return polygons;
  67376. };
  67377. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  67378. // new polygons are filtered down to the bottom of the tree and become new
  67379. // nodes there. Each set of polygons is partitioned using the first polygon
  67380. // (no heuristic is used to pick a good split).
  67381. Node.prototype.build = function (polygons) {
  67382. if (!polygons.length)
  67383. return;
  67384. if (!this.plane)
  67385. this.plane = polygons[0].plane.clone();
  67386. var front = new Array(), back = new Array();
  67387. for (var i = 0; i < polygons.length; i++) {
  67388. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  67389. }
  67390. if (front.length) {
  67391. if (!this.front)
  67392. this.front = new Node();
  67393. this.front.build(front);
  67394. }
  67395. if (back.length) {
  67396. if (!this.back)
  67397. this.back = new Node();
  67398. this.back.build(back);
  67399. }
  67400. };
  67401. return Node;
  67402. }());
  67403. var CSG = /** @class */ (function () {
  67404. function CSG() {
  67405. this.polygons = new Array();
  67406. }
  67407. // Convert BABYLON.Mesh to BABYLON.CSG
  67408. CSG.FromMesh = function (mesh) {
  67409. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  67410. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  67411. if (mesh instanceof BABYLON.Mesh) {
  67412. mesh.computeWorldMatrix(true);
  67413. matrix = mesh.getWorldMatrix();
  67414. meshPosition = mesh.position.clone();
  67415. meshRotation = mesh.rotation.clone();
  67416. if (mesh.rotationQuaternion) {
  67417. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  67418. }
  67419. meshScaling = mesh.scaling.clone();
  67420. }
  67421. else {
  67422. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  67423. }
  67424. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67425. var subMeshes = mesh.subMeshes;
  67426. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  67427. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  67428. vertices = [];
  67429. for (var j = 0; j < 3; j++) {
  67430. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  67431. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  67432. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  67433. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  67434. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  67435. vertex = new Vertex(position, normal, uv);
  67436. vertices.push(vertex);
  67437. }
  67438. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  67439. // To handle the case of degenerated triangle
  67440. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  67441. if (polygon.plane)
  67442. polygons.push(polygon);
  67443. }
  67444. }
  67445. var csg = CSG.FromPolygons(polygons);
  67446. csg.matrix = matrix;
  67447. csg.position = meshPosition;
  67448. csg.rotation = meshRotation;
  67449. csg.scaling = meshScaling;
  67450. csg.rotationQuaternion = meshRotationQuaternion;
  67451. currentCSGMeshId++;
  67452. return csg;
  67453. };
  67454. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  67455. CSG.FromPolygons = function (polygons) {
  67456. var csg = new CSG();
  67457. csg.polygons = polygons;
  67458. return csg;
  67459. };
  67460. CSG.prototype.clone = function () {
  67461. var csg = new CSG();
  67462. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  67463. csg.copyTransformAttributes(this);
  67464. return csg;
  67465. };
  67466. CSG.prototype.union = function (csg) {
  67467. var a = new Node(this.clone().polygons);
  67468. var b = new Node(csg.clone().polygons);
  67469. a.clipTo(b);
  67470. b.clipTo(a);
  67471. b.invert();
  67472. b.clipTo(a);
  67473. b.invert();
  67474. a.build(b.allPolygons());
  67475. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67476. };
  67477. CSG.prototype.unionInPlace = function (csg) {
  67478. var a = new Node(this.polygons);
  67479. var b = new Node(csg.polygons);
  67480. a.clipTo(b);
  67481. b.clipTo(a);
  67482. b.invert();
  67483. b.clipTo(a);
  67484. b.invert();
  67485. a.build(b.allPolygons());
  67486. this.polygons = a.allPolygons();
  67487. };
  67488. CSG.prototype.subtract = function (csg) {
  67489. var a = new Node(this.clone().polygons);
  67490. var b = new Node(csg.clone().polygons);
  67491. a.invert();
  67492. a.clipTo(b);
  67493. b.clipTo(a);
  67494. b.invert();
  67495. b.clipTo(a);
  67496. b.invert();
  67497. a.build(b.allPolygons());
  67498. a.invert();
  67499. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67500. };
  67501. CSG.prototype.subtractInPlace = function (csg) {
  67502. var a = new Node(this.polygons);
  67503. var b = new Node(csg.polygons);
  67504. a.invert();
  67505. a.clipTo(b);
  67506. b.clipTo(a);
  67507. b.invert();
  67508. b.clipTo(a);
  67509. b.invert();
  67510. a.build(b.allPolygons());
  67511. a.invert();
  67512. this.polygons = a.allPolygons();
  67513. };
  67514. CSG.prototype.intersect = function (csg) {
  67515. var a = new Node(this.clone().polygons);
  67516. var b = new Node(csg.clone().polygons);
  67517. a.invert();
  67518. b.clipTo(a);
  67519. b.invert();
  67520. a.clipTo(b);
  67521. b.clipTo(a);
  67522. a.build(b.allPolygons());
  67523. a.invert();
  67524. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67525. };
  67526. CSG.prototype.intersectInPlace = function (csg) {
  67527. var a = new Node(this.polygons);
  67528. var b = new Node(csg.polygons);
  67529. a.invert();
  67530. b.clipTo(a);
  67531. b.invert();
  67532. a.clipTo(b);
  67533. b.clipTo(a);
  67534. a.build(b.allPolygons());
  67535. a.invert();
  67536. this.polygons = a.allPolygons();
  67537. };
  67538. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  67539. // not modified.
  67540. CSG.prototype.inverse = function () {
  67541. var csg = this.clone();
  67542. csg.inverseInPlace();
  67543. return csg;
  67544. };
  67545. CSG.prototype.inverseInPlace = function () {
  67546. this.polygons.map(function (p) { p.flip(); });
  67547. };
  67548. // This is used to keep meshes transformations so they can be restored
  67549. // when we build back a Babylon Mesh
  67550. // NB : All CSG operations are performed in world coordinates
  67551. CSG.prototype.copyTransformAttributes = function (csg) {
  67552. this.matrix = csg.matrix;
  67553. this.position = csg.position;
  67554. this.rotation = csg.rotation;
  67555. this.scaling = csg.scaling;
  67556. this.rotationQuaternion = csg.rotationQuaternion;
  67557. return this;
  67558. };
  67559. // Build Raw mesh from CSG
  67560. // Coordinates here are in world space
  67561. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  67562. var matrix = this.matrix.clone();
  67563. matrix.invert();
  67564. 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;
  67565. if (keepSubMeshes) {
  67566. // Sort Polygons, since subMeshes are indices range
  67567. polygons.sort(function (a, b) {
  67568. if (a.shared.meshId === b.shared.meshId) {
  67569. return a.shared.subMeshId - b.shared.subMeshId;
  67570. }
  67571. else {
  67572. return a.shared.meshId - b.shared.meshId;
  67573. }
  67574. });
  67575. }
  67576. for (var i = 0, il = polygons.length; i < il; i++) {
  67577. polygon = polygons[i];
  67578. // Building SubMeshes
  67579. if (!subMesh_dict[polygon.shared.meshId]) {
  67580. subMesh_dict[polygon.shared.meshId] = {};
  67581. }
  67582. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  67583. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  67584. indexStart: +Infinity,
  67585. indexEnd: -Infinity,
  67586. materialIndex: polygon.shared.materialIndex
  67587. };
  67588. }
  67589. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  67590. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  67591. polygonIndices[0] = 0;
  67592. polygonIndices[1] = j - 1;
  67593. polygonIndices[2] = j;
  67594. for (var k = 0; k < 3; k++) {
  67595. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  67596. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  67597. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  67598. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  67599. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  67600. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  67601. // Check if 2 points can be merged
  67602. if (!(typeof vertex_idx !== 'undefined' &&
  67603. normals[vertex_idx * 3] === localNormal.x &&
  67604. normals[vertex_idx * 3 + 1] === localNormal.y &&
  67605. normals[vertex_idx * 3 + 2] === localNormal.z &&
  67606. uvs[vertex_idx * 2] === uv.x &&
  67607. uvs[vertex_idx * 2 + 1] === uv.y)) {
  67608. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  67609. uvs.push(uv.x, uv.y);
  67610. normals.push(normal.x, normal.y, normal.z);
  67611. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  67612. }
  67613. indices.push(vertex_idx);
  67614. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  67615. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  67616. currentIndex++;
  67617. }
  67618. }
  67619. }
  67620. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  67621. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  67622. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  67623. mesh.setIndices(indices, null);
  67624. if (keepSubMeshes) {
  67625. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  67626. var materialIndexOffset = 0, materialMaxIndex;
  67627. mesh.subMeshes = new Array();
  67628. for (var m in subMesh_dict) {
  67629. materialMaxIndex = -1;
  67630. for (var sm in subMesh_dict[m]) {
  67631. subMesh_obj = subMesh_dict[m][sm];
  67632. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  67633. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  67634. }
  67635. materialIndexOffset += ++materialMaxIndex;
  67636. }
  67637. }
  67638. return mesh;
  67639. };
  67640. // Build Mesh from CSG taking material and transforms into account
  67641. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  67642. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  67643. mesh.material = material;
  67644. mesh.position.copyFrom(this.position);
  67645. mesh.rotation.copyFrom(this.rotation);
  67646. if (this.rotationQuaternion) {
  67647. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  67648. }
  67649. mesh.scaling.copyFrom(this.scaling);
  67650. mesh.computeWorldMatrix(true);
  67651. return mesh;
  67652. };
  67653. return CSG;
  67654. }());
  67655. BABYLON.CSG = CSG;
  67656. })(BABYLON || (BABYLON = {}));
  67657. //# sourceMappingURL=babylon.csg.js.map
  67658. var BABYLON;
  67659. (function (BABYLON) {
  67660. var LensFlare = /** @class */ (function () {
  67661. function LensFlare(size, position, color, imgUrl, system) {
  67662. this.size = size;
  67663. this.position = position;
  67664. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  67665. this.color = color || new BABYLON.Color3(1, 1, 1);
  67666. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  67667. this._system = system;
  67668. system.lensFlares.push(this);
  67669. }
  67670. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  67671. return new LensFlare(size, position, color, imgUrl, system);
  67672. };
  67673. LensFlare.prototype.dispose = function () {
  67674. if (this.texture) {
  67675. this.texture.dispose();
  67676. }
  67677. // Remove from scene
  67678. var index = this._system.lensFlares.indexOf(this);
  67679. this._system.lensFlares.splice(index, 1);
  67680. };
  67681. ;
  67682. return LensFlare;
  67683. }());
  67684. BABYLON.LensFlare = LensFlare;
  67685. })(BABYLON || (BABYLON = {}));
  67686. //# sourceMappingURL=babylon.lensFlare.js.map
  67687. var BABYLON;
  67688. (function (BABYLON) {
  67689. var LensFlareSystem = /** @class */ (function () {
  67690. function LensFlareSystem(name, emitter, scene) {
  67691. this.name = name;
  67692. this.lensFlares = new Array();
  67693. this.borderLimit = 300;
  67694. this.viewportBorder = 0;
  67695. this.layerMask = 0x0FFFFFFF;
  67696. this._vertexBuffers = {};
  67697. this._isEnabled = true;
  67698. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67699. this._emitter = emitter;
  67700. this.id = name;
  67701. scene.lensFlareSystems.push(this);
  67702. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  67703. var engine = scene.getEngine();
  67704. // VBO
  67705. var vertices = [];
  67706. vertices.push(1, 1);
  67707. vertices.push(-1, 1);
  67708. vertices.push(-1, -1);
  67709. vertices.push(1, -1);
  67710. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67711. // Indices
  67712. var indices = [];
  67713. indices.push(0);
  67714. indices.push(1);
  67715. indices.push(2);
  67716. indices.push(0);
  67717. indices.push(2);
  67718. indices.push(3);
  67719. this._indexBuffer = engine.createIndexBuffer(indices);
  67720. // Effects
  67721. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  67722. }
  67723. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  67724. get: function () {
  67725. return this._isEnabled;
  67726. },
  67727. set: function (value) {
  67728. this._isEnabled = value;
  67729. },
  67730. enumerable: true,
  67731. configurable: true
  67732. });
  67733. LensFlareSystem.prototype.getScene = function () {
  67734. return this._scene;
  67735. };
  67736. LensFlareSystem.prototype.getEmitter = function () {
  67737. return this._emitter;
  67738. };
  67739. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  67740. this._emitter = newEmitter;
  67741. };
  67742. LensFlareSystem.prototype.getEmitterPosition = function () {
  67743. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  67744. };
  67745. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  67746. var position = this.getEmitterPosition();
  67747. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  67748. this._positionX = position.x;
  67749. this._positionY = position.y;
  67750. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  67751. if (this.viewportBorder > 0) {
  67752. globalViewport.x -= this.viewportBorder;
  67753. globalViewport.y -= this.viewportBorder;
  67754. globalViewport.width += this.viewportBorder * 2;
  67755. globalViewport.height += this.viewportBorder * 2;
  67756. position.x += this.viewportBorder;
  67757. position.y += this.viewportBorder;
  67758. this._positionX += this.viewportBorder;
  67759. this._positionY += this.viewportBorder;
  67760. }
  67761. if (position.z > 0) {
  67762. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  67763. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  67764. return true;
  67765. }
  67766. return true;
  67767. }
  67768. return false;
  67769. };
  67770. LensFlareSystem.prototype._isVisible = function () {
  67771. if (!this._isEnabled || !this._scene.activeCamera) {
  67772. return false;
  67773. }
  67774. var emitterPosition = this.getEmitterPosition();
  67775. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  67776. var distance = direction.length();
  67777. direction.normalize();
  67778. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  67779. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  67780. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  67781. };
  67782. LensFlareSystem.prototype.render = function () {
  67783. if (!this._effect.isReady() || !this._scene.activeCamera)
  67784. return false;
  67785. var engine = this._scene.getEngine();
  67786. var viewport = this._scene.activeCamera.viewport;
  67787. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  67788. // Position
  67789. if (!this.computeEffectivePosition(globalViewport)) {
  67790. return false;
  67791. }
  67792. // Visibility
  67793. if (!this._isVisible()) {
  67794. return false;
  67795. }
  67796. // Intensity
  67797. var awayX;
  67798. var awayY;
  67799. if (this._positionX < this.borderLimit + globalViewport.x) {
  67800. awayX = this.borderLimit + globalViewport.x - this._positionX;
  67801. }
  67802. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  67803. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  67804. }
  67805. else {
  67806. awayX = 0;
  67807. }
  67808. if (this._positionY < this.borderLimit + globalViewport.y) {
  67809. awayY = this.borderLimit + globalViewport.y - this._positionY;
  67810. }
  67811. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  67812. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  67813. }
  67814. else {
  67815. awayY = 0;
  67816. }
  67817. var away = (awayX > awayY) ? awayX : awayY;
  67818. away -= this.viewportBorder;
  67819. if (away > this.borderLimit) {
  67820. away = this.borderLimit;
  67821. }
  67822. var intensity = 1.0 - (away / this.borderLimit);
  67823. if (intensity < 0) {
  67824. return false;
  67825. }
  67826. if (intensity > 1.0) {
  67827. intensity = 1.0;
  67828. }
  67829. if (this.viewportBorder > 0) {
  67830. globalViewport.x += this.viewportBorder;
  67831. globalViewport.y += this.viewportBorder;
  67832. globalViewport.width -= this.viewportBorder * 2;
  67833. globalViewport.height -= this.viewportBorder * 2;
  67834. this._positionX -= this.viewportBorder;
  67835. this._positionY -= this.viewportBorder;
  67836. }
  67837. // Position
  67838. var centerX = globalViewport.x + globalViewport.width / 2;
  67839. var centerY = globalViewport.y + globalViewport.height / 2;
  67840. var distX = centerX - this._positionX;
  67841. var distY = centerY - this._positionY;
  67842. // Effects
  67843. engine.enableEffect(this._effect);
  67844. engine.setState(false);
  67845. engine.setDepthBuffer(false);
  67846. // VBOs
  67847. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  67848. // Flares
  67849. for (var index = 0; index < this.lensFlares.length; index++) {
  67850. var flare = this.lensFlares[index];
  67851. engine.setAlphaMode(flare.alphaMode);
  67852. var x = centerX - (distX * flare.position);
  67853. var y = centerY - (distY * flare.position);
  67854. var cw = flare.size;
  67855. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  67856. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  67857. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  67858. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  67859. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  67860. // Texture
  67861. this._effect.setTexture("textureSampler", flare.texture);
  67862. // Color
  67863. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  67864. // Draw order
  67865. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67866. }
  67867. engine.setDepthBuffer(true);
  67868. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67869. return true;
  67870. };
  67871. LensFlareSystem.prototype.dispose = function () {
  67872. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67873. if (vertexBuffer) {
  67874. vertexBuffer.dispose();
  67875. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67876. }
  67877. if (this._indexBuffer) {
  67878. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67879. this._indexBuffer = null;
  67880. }
  67881. while (this.lensFlares.length) {
  67882. this.lensFlares[0].dispose();
  67883. }
  67884. // Remove from scene
  67885. var index = this._scene.lensFlareSystems.indexOf(this);
  67886. this._scene.lensFlareSystems.splice(index, 1);
  67887. };
  67888. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  67889. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  67890. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  67891. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  67892. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  67893. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  67894. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  67895. var parsedFlare = parsedLensFlareSystem.flares[index];
  67896. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  67897. }
  67898. return lensFlareSystem;
  67899. };
  67900. LensFlareSystem.prototype.serialize = function () {
  67901. var serializationObject = {};
  67902. serializationObject.id = this.id;
  67903. serializationObject.name = this.name;
  67904. serializationObject.emitterId = this.getEmitter().id;
  67905. serializationObject.borderLimit = this.borderLimit;
  67906. serializationObject.flares = [];
  67907. for (var index = 0; index < this.lensFlares.length; index++) {
  67908. var flare = this.lensFlares[index];
  67909. serializationObject.flares.push({
  67910. size: flare.size,
  67911. position: flare.position,
  67912. color: flare.color.asArray(),
  67913. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  67914. });
  67915. }
  67916. return serializationObject;
  67917. };
  67918. return LensFlareSystem;
  67919. }());
  67920. BABYLON.LensFlareSystem = LensFlareSystem;
  67921. })(BABYLON || (BABYLON = {}));
  67922. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  67923. var BABYLON;
  67924. (function (BABYLON) {
  67925. /**
  67926. * This is a holder class for the physics joint created by the physics plugin.
  67927. * It holds a set of functions to control the underlying joint.
  67928. */
  67929. var PhysicsJoint = /** @class */ (function () {
  67930. function PhysicsJoint(type, jointData) {
  67931. this.type = type;
  67932. this.jointData = jointData;
  67933. jointData.nativeParams = jointData.nativeParams || {};
  67934. }
  67935. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  67936. get: function () {
  67937. return this._physicsJoint;
  67938. },
  67939. set: function (newJoint) {
  67940. if (this._physicsJoint) {
  67941. //remove from the wolrd
  67942. }
  67943. this._physicsJoint = newJoint;
  67944. },
  67945. enumerable: true,
  67946. configurable: true
  67947. });
  67948. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  67949. set: function (physicsPlugin) {
  67950. this._physicsPlugin = physicsPlugin;
  67951. },
  67952. enumerable: true,
  67953. configurable: true
  67954. });
  67955. /**
  67956. * Execute a function that is physics-plugin specific.
  67957. * @param {Function} func the function that will be executed.
  67958. * It accepts two parameters: the physics world and the physics joint.
  67959. */
  67960. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  67961. func(this._physicsPlugin.world, this._physicsJoint);
  67962. };
  67963. //TODO check if the native joints are the same
  67964. //Joint Types
  67965. PhysicsJoint.DistanceJoint = 0;
  67966. PhysicsJoint.HingeJoint = 1;
  67967. PhysicsJoint.BallAndSocketJoint = 2;
  67968. PhysicsJoint.WheelJoint = 3;
  67969. PhysicsJoint.SliderJoint = 4;
  67970. //OIMO
  67971. PhysicsJoint.PrismaticJoint = 5;
  67972. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  67973. PhysicsJoint.UniversalJoint = 6;
  67974. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  67975. //Cannon
  67976. //Similar to a Ball-Joint. Different in params
  67977. PhysicsJoint.PointToPointJoint = 8;
  67978. //Cannon only at the moment
  67979. PhysicsJoint.SpringJoint = 9;
  67980. PhysicsJoint.LockJoint = 10;
  67981. return PhysicsJoint;
  67982. }());
  67983. BABYLON.PhysicsJoint = PhysicsJoint;
  67984. /**
  67985. * A class representing a physics distance joint.
  67986. */
  67987. var DistanceJoint = /** @class */ (function (_super) {
  67988. __extends(DistanceJoint, _super);
  67989. function DistanceJoint(jointData) {
  67990. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  67991. }
  67992. /**
  67993. * Update the predefined distance.
  67994. */
  67995. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  67996. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  67997. };
  67998. return DistanceJoint;
  67999. }(PhysicsJoint));
  68000. BABYLON.DistanceJoint = DistanceJoint;
  68001. var MotorEnabledJoint = /** @class */ (function (_super) {
  68002. __extends(MotorEnabledJoint, _super);
  68003. function MotorEnabledJoint(type, jointData) {
  68004. return _super.call(this, type, jointData) || this;
  68005. }
  68006. /**
  68007. * Set the motor values.
  68008. * Attention, this function is plugin specific. Engines won't react 100% the same.
  68009. * @param {number} force the force to apply
  68010. * @param {number} maxForce max force for this motor.
  68011. */
  68012. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  68013. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  68014. };
  68015. /**
  68016. * Set the motor's limits.
  68017. * Attention, this function is plugin specific. Engines won't react 100% the same.
  68018. */
  68019. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  68020. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  68021. };
  68022. return MotorEnabledJoint;
  68023. }(PhysicsJoint));
  68024. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  68025. /**
  68026. * This class represents a single hinge physics joint
  68027. */
  68028. var HingeJoint = /** @class */ (function (_super) {
  68029. __extends(HingeJoint, _super);
  68030. function HingeJoint(jointData) {
  68031. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  68032. }
  68033. /**
  68034. * Set the motor values.
  68035. * Attention, this function is plugin specific. Engines won't react 100% the same.
  68036. * @param {number} force the force to apply
  68037. * @param {number} maxForce max force for this motor.
  68038. */
  68039. HingeJoint.prototype.setMotor = function (force, maxForce) {
  68040. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  68041. };
  68042. /**
  68043. * Set the motor's limits.
  68044. * Attention, this function is plugin specific. Engines won't react 100% the same.
  68045. */
  68046. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  68047. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  68048. };
  68049. return HingeJoint;
  68050. }(MotorEnabledJoint));
  68051. BABYLON.HingeJoint = HingeJoint;
  68052. /**
  68053. * This class represents a dual hinge physics joint (same as wheel joint)
  68054. */
  68055. var Hinge2Joint = /** @class */ (function (_super) {
  68056. __extends(Hinge2Joint, _super);
  68057. function Hinge2Joint(jointData) {
  68058. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  68059. }
  68060. /**
  68061. * Set the motor values.
  68062. * Attention, this function is plugin specific. Engines won't react 100% the same.
  68063. * @param {number} force the force to apply
  68064. * @param {number} maxForce max force for this motor.
  68065. * @param {motorIndex} the motor's index, 0 or 1.
  68066. */
  68067. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  68068. if (motorIndex === void 0) { motorIndex = 0; }
  68069. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  68070. };
  68071. /**
  68072. * Set the motor limits.
  68073. * Attention, this function is plugin specific. Engines won't react 100% the same.
  68074. * @param {number} upperLimit the upper limit
  68075. * @param {number} lowerLimit lower limit
  68076. * @param {motorIndex} the motor's index, 0 or 1.
  68077. */
  68078. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  68079. if (motorIndex === void 0) { motorIndex = 0; }
  68080. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  68081. };
  68082. return Hinge2Joint;
  68083. }(MotorEnabledJoint));
  68084. BABYLON.Hinge2Joint = Hinge2Joint;
  68085. })(BABYLON || (BABYLON = {}));
  68086. //# sourceMappingURL=babylon.physicsJoint.js.map
  68087. var BABYLON;
  68088. (function (BABYLON) {
  68089. var PhysicsImpostor = /** @class */ (function () {
  68090. function PhysicsImpostor(object, type, _options, _scene) {
  68091. if (_options === void 0) { _options = { mass: 0 }; }
  68092. var _this = this;
  68093. this.object = object;
  68094. this.type = type;
  68095. this._options = _options;
  68096. this._scene = _scene;
  68097. this._bodyUpdateRequired = false;
  68098. this._onBeforePhysicsStepCallbacks = new Array();
  68099. this._onAfterPhysicsStepCallbacks = new Array();
  68100. this._onPhysicsCollideCallbacks = [];
  68101. this._deltaPosition = BABYLON.Vector3.Zero();
  68102. this._isDisposed = false;
  68103. //temp variables for parent rotation calculations
  68104. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  68105. this._tmpQuat = new BABYLON.Quaternion();
  68106. this._tmpQuat2 = new BABYLON.Quaternion();
  68107. /**
  68108. * this function is executed by the physics engine.
  68109. */
  68110. this.beforeStep = function () {
  68111. if (!_this._physicsEngine) {
  68112. return;
  68113. }
  68114. _this.object.translate(_this._deltaPosition, -1);
  68115. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  68116. _this.object.computeWorldMatrix(false);
  68117. if (_this.object.parent && _this.object.rotationQuaternion) {
  68118. _this.getParentsRotation();
  68119. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  68120. }
  68121. else {
  68122. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  68123. }
  68124. if (!_this._options.disableBidirectionalTransformation) {
  68125. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  68126. }
  68127. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  68128. func(_this);
  68129. });
  68130. };
  68131. /**
  68132. * this function is executed by the physics engine.
  68133. */
  68134. this.afterStep = function () {
  68135. if (!_this._physicsEngine) {
  68136. return;
  68137. }
  68138. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  68139. func(_this);
  68140. });
  68141. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  68142. // object has now its world rotation. needs to be converted to local.
  68143. if (_this.object.parent && _this.object.rotationQuaternion) {
  68144. _this.getParentsRotation();
  68145. _this._tmpQuat.conjugateInPlace();
  68146. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  68147. }
  68148. // take the position set and make it the absolute position of this object.
  68149. _this.object.setAbsolutePosition(_this.object.position);
  68150. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  68151. _this.object.translate(_this._deltaPosition, 1);
  68152. };
  68153. /**
  68154. * Legacy collision detection event support
  68155. */
  68156. this.onCollideEvent = null;
  68157. //event and body object due to cannon's event-based architecture.
  68158. this.onCollide = function (e) {
  68159. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  68160. return;
  68161. }
  68162. if (!_this._physicsEngine) {
  68163. return;
  68164. }
  68165. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  68166. if (otherImpostor) {
  68167. // Legacy collision detection event support
  68168. if (_this.onCollideEvent) {
  68169. _this.onCollideEvent(_this, otherImpostor);
  68170. }
  68171. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  68172. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  68173. }).forEach(function (obj) {
  68174. obj.callback(_this, otherImpostor);
  68175. });
  68176. }
  68177. };
  68178. //sanity check!
  68179. if (!this.object) {
  68180. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  68181. return;
  68182. }
  68183. //legacy support for old syntax.
  68184. if (!this._scene && object.getScene) {
  68185. this._scene = object.getScene();
  68186. }
  68187. if (!this._scene) {
  68188. return;
  68189. }
  68190. this._physicsEngine = this._scene.getPhysicsEngine();
  68191. if (!this._physicsEngine) {
  68192. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  68193. }
  68194. else {
  68195. //set the object's quaternion, if not set
  68196. if (!this.object.rotationQuaternion) {
  68197. if (this.object.rotation) {
  68198. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  68199. }
  68200. else {
  68201. this.object.rotationQuaternion = new BABYLON.Quaternion();
  68202. }
  68203. }
  68204. //default options params
  68205. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  68206. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  68207. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  68208. this._joints = [];
  68209. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  68210. if (!this.object.parent || this._options.ignoreParent) {
  68211. this._init();
  68212. }
  68213. else if (this.object.parent.physicsImpostor) {
  68214. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  68215. }
  68216. }
  68217. }
  68218. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  68219. get: function () {
  68220. return this._isDisposed;
  68221. },
  68222. enumerable: true,
  68223. configurable: true
  68224. });
  68225. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  68226. get: function () {
  68227. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  68228. },
  68229. set: function (value) {
  68230. this.setMass(value);
  68231. },
  68232. enumerable: true,
  68233. configurable: true
  68234. });
  68235. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  68236. get: function () {
  68237. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  68238. },
  68239. set: function (value) {
  68240. if (!this._physicsEngine) {
  68241. return;
  68242. }
  68243. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  68244. },
  68245. enumerable: true,
  68246. configurable: true
  68247. });
  68248. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  68249. get: function () {
  68250. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  68251. },
  68252. set: function (value) {
  68253. if (!this._physicsEngine) {
  68254. return;
  68255. }
  68256. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  68257. },
  68258. enumerable: true,
  68259. configurable: true
  68260. });
  68261. /**
  68262. * This function will completly initialize this impostor.
  68263. * It will create a new body - but only if this mesh has no parent.
  68264. * If it has, this impostor will not be used other than to define the impostor
  68265. * of the child mesh.
  68266. */
  68267. PhysicsImpostor.prototype._init = function () {
  68268. if (!this._physicsEngine) {
  68269. return;
  68270. }
  68271. this._physicsEngine.removeImpostor(this);
  68272. this.physicsBody = null;
  68273. this._parent = this._parent || this._getPhysicsParent();
  68274. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  68275. this._physicsEngine.addImpostor(this);
  68276. }
  68277. };
  68278. PhysicsImpostor.prototype._getPhysicsParent = function () {
  68279. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  68280. var parentMesh = this.object.parent;
  68281. return parentMesh.physicsImpostor;
  68282. }
  68283. return null;
  68284. };
  68285. /**
  68286. * Should a new body be generated.
  68287. */
  68288. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  68289. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  68290. };
  68291. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  68292. this.forceUpdate();
  68293. };
  68294. /**
  68295. * Force a regeneration of this or the parent's impostor's body.
  68296. * Use under cautious - This will remove all joints already implemented.
  68297. */
  68298. PhysicsImpostor.prototype.forceUpdate = function () {
  68299. this._init();
  68300. if (this.parent && !this._options.ignoreParent) {
  68301. this.parent.forceUpdate();
  68302. }
  68303. };
  68304. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  68305. /*public get mesh(): AbstractMesh {
  68306. return this._mesh;
  68307. }*/
  68308. /**
  68309. * Gets the body that holds this impostor. Either its own, or its parent.
  68310. */
  68311. get: function () {
  68312. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  68313. },
  68314. /**
  68315. * Set the physics body. Used mainly by the physics engine/plugin
  68316. */
  68317. set: function (physicsBody) {
  68318. if (this._physicsBody && this._physicsEngine) {
  68319. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  68320. }
  68321. this._physicsBody = physicsBody;
  68322. this.resetUpdateFlags();
  68323. },
  68324. enumerable: true,
  68325. configurable: true
  68326. });
  68327. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  68328. get: function () {
  68329. return !this._options.ignoreParent && this._parent ? this._parent : null;
  68330. },
  68331. set: function (value) {
  68332. this._parent = value;
  68333. },
  68334. enumerable: true,
  68335. configurable: true
  68336. });
  68337. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  68338. this._bodyUpdateRequired = false;
  68339. };
  68340. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  68341. if (this.object.getBoundingInfo) {
  68342. var q = this.object.rotationQuaternion;
  68343. //reset rotation
  68344. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  68345. //calculate the world matrix with no rotation
  68346. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  68347. var boundingInfo = this.object.getBoundingInfo();
  68348. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  68349. //bring back the rotation
  68350. this.object.rotationQuaternion = q;
  68351. //calculate the world matrix with the new rotation
  68352. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  68353. return size;
  68354. }
  68355. else {
  68356. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  68357. }
  68358. };
  68359. PhysicsImpostor.prototype.getObjectCenter = function () {
  68360. if (this.object.getBoundingInfo) {
  68361. var boundingInfo = this.object.getBoundingInfo();
  68362. return boundingInfo.boundingBox.centerWorld;
  68363. }
  68364. else {
  68365. return this.object.position;
  68366. }
  68367. };
  68368. /**
  68369. * Get a specific parametes from the options parameter.
  68370. */
  68371. PhysicsImpostor.prototype.getParam = function (paramName) {
  68372. return this._options[paramName];
  68373. };
  68374. /**
  68375. * Sets a specific parameter in the options given to the physics plugin
  68376. */
  68377. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  68378. this._options[paramName] = value;
  68379. this._bodyUpdateRequired = true;
  68380. };
  68381. /**
  68382. * Specifically change the body's mass option. Won't recreate the physics body object
  68383. */
  68384. PhysicsImpostor.prototype.setMass = function (mass) {
  68385. if (this.getParam("mass") !== mass) {
  68386. this.setParam("mass", mass);
  68387. }
  68388. if (this._physicsEngine) {
  68389. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  68390. }
  68391. };
  68392. PhysicsImpostor.prototype.getLinearVelocity = function () {
  68393. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  68394. };
  68395. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  68396. if (this._physicsEngine) {
  68397. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  68398. }
  68399. };
  68400. PhysicsImpostor.prototype.getAngularVelocity = function () {
  68401. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  68402. };
  68403. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  68404. if (this._physicsEngine) {
  68405. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  68406. }
  68407. };
  68408. /**
  68409. * Execute a function with the physics plugin native code.
  68410. * Provide a function the will have two variables - the world object and the physics body object.
  68411. */
  68412. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  68413. if (this._physicsEngine) {
  68414. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  68415. }
  68416. };
  68417. /**
  68418. * Register a function that will be executed before the physics world is stepping forward.
  68419. */
  68420. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  68421. this._onBeforePhysicsStepCallbacks.push(func);
  68422. };
  68423. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  68424. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  68425. if (index > -1) {
  68426. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  68427. }
  68428. else {
  68429. BABYLON.Tools.Warn("Function to remove was not found");
  68430. }
  68431. };
  68432. /**
  68433. * Register a function that will be executed after the physics step
  68434. */
  68435. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  68436. this._onAfterPhysicsStepCallbacks.push(func);
  68437. };
  68438. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  68439. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  68440. if (index > -1) {
  68441. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  68442. }
  68443. else {
  68444. BABYLON.Tools.Warn("Function to remove was not found");
  68445. }
  68446. };
  68447. /**
  68448. * register a function that will be executed when this impostor collides against a different body.
  68449. */
  68450. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  68451. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  68452. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  68453. };
  68454. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  68455. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  68456. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  68457. if (index > -1) {
  68458. this._onPhysicsCollideCallbacks.splice(index, 1);
  68459. }
  68460. else {
  68461. BABYLON.Tools.Warn("Function to remove was not found");
  68462. }
  68463. };
  68464. PhysicsImpostor.prototype.getParentsRotation = function () {
  68465. var parent = this.object.parent;
  68466. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  68467. while (parent) {
  68468. if (parent.rotationQuaternion) {
  68469. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  68470. }
  68471. else {
  68472. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  68473. }
  68474. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  68475. parent = parent.parent;
  68476. }
  68477. return this._tmpQuat;
  68478. };
  68479. /**
  68480. * Apply a force
  68481. */
  68482. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  68483. if (this._physicsEngine) {
  68484. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  68485. }
  68486. return this;
  68487. };
  68488. /**
  68489. * Apply an impulse
  68490. */
  68491. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  68492. if (this._physicsEngine) {
  68493. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  68494. }
  68495. return this;
  68496. };
  68497. /**
  68498. * A help function to create a joint.
  68499. */
  68500. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  68501. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  68502. this.addJoint(otherImpostor, joint);
  68503. return this;
  68504. };
  68505. /**
  68506. * Add a joint to this impostor with a different impostor.
  68507. */
  68508. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  68509. this._joints.push({
  68510. otherImpostor: otherImpostor,
  68511. joint: joint
  68512. });
  68513. if (this._physicsEngine) {
  68514. this._physicsEngine.addJoint(this, otherImpostor, joint);
  68515. }
  68516. return this;
  68517. };
  68518. /**
  68519. * Will keep this body still, in a sleep mode.
  68520. */
  68521. PhysicsImpostor.prototype.sleep = function () {
  68522. if (this._physicsEngine) {
  68523. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  68524. }
  68525. return this;
  68526. };
  68527. /**
  68528. * Wake the body up.
  68529. */
  68530. PhysicsImpostor.prototype.wakeUp = function () {
  68531. if (this._physicsEngine) {
  68532. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  68533. }
  68534. return this;
  68535. };
  68536. PhysicsImpostor.prototype.clone = function (newObject) {
  68537. if (!newObject)
  68538. return null;
  68539. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  68540. };
  68541. PhysicsImpostor.prototype.dispose = function () {
  68542. var _this = this;
  68543. //no dispose if no physics engine is available.
  68544. if (!this._physicsEngine) {
  68545. return;
  68546. }
  68547. this._joints.forEach(function (j) {
  68548. if (_this._physicsEngine) {
  68549. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  68550. }
  68551. });
  68552. //dispose the physics body
  68553. this._physicsEngine.removeImpostor(this);
  68554. if (this.parent) {
  68555. this.parent.forceUpdate();
  68556. }
  68557. else {
  68558. /*this._object.getChildMeshes().forEach(function(mesh) {
  68559. if (mesh.physicsImpostor) {
  68560. if (disposeChildren) {
  68561. mesh.physicsImpostor.dispose();
  68562. mesh.physicsImpostor = null;
  68563. }
  68564. }
  68565. })*/
  68566. }
  68567. this._isDisposed = true;
  68568. };
  68569. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  68570. this._deltaPosition.copyFrom(position);
  68571. };
  68572. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  68573. if (!this._deltaRotation) {
  68574. this._deltaRotation = new BABYLON.Quaternion();
  68575. }
  68576. this._deltaRotation.copyFrom(rotation);
  68577. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  68578. };
  68579. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  68580. if (this._physicsEngine) {
  68581. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  68582. }
  68583. return this;
  68584. };
  68585. PhysicsImpostor.prototype.getRadius = function () {
  68586. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  68587. };
  68588. /**
  68589. * Sync a bone with this impostor
  68590. * @param bone The bone to sync to the impostor.
  68591. * @param boneMesh The mesh that the bone is influencing.
  68592. * @param jointPivot The pivot of the joint / bone in local space.
  68593. * @param distToJoint Optional distance from the impostor to the joint.
  68594. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  68595. */
  68596. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  68597. var tempVec = PhysicsImpostor._tmpVecs[0];
  68598. var mesh = this.object;
  68599. if (mesh.rotationQuaternion) {
  68600. if (adjustRotation) {
  68601. var tempQuat = PhysicsImpostor._tmpQuat;
  68602. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  68603. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  68604. }
  68605. else {
  68606. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  68607. }
  68608. }
  68609. tempVec.x = 0;
  68610. tempVec.y = 0;
  68611. tempVec.z = 0;
  68612. if (jointPivot) {
  68613. tempVec.x = jointPivot.x;
  68614. tempVec.y = jointPivot.y;
  68615. tempVec.z = jointPivot.z;
  68616. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  68617. if (distToJoint === undefined || distToJoint === null) {
  68618. distToJoint = jointPivot.length();
  68619. }
  68620. tempVec.x *= distToJoint;
  68621. tempVec.y *= distToJoint;
  68622. tempVec.z *= distToJoint;
  68623. }
  68624. if (bone.getParent()) {
  68625. tempVec.addInPlace(mesh.getAbsolutePosition());
  68626. bone.setAbsolutePosition(tempVec, boneMesh);
  68627. }
  68628. else {
  68629. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  68630. boneMesh.position.x -= tempVec.x;
  68631. boneMesh.position.y -= tempVec.y;
  68632. boneMesh.position.z -= tempVec.z;
  68633. }
  68634. };
  68635. /**
  68636. * Sync impostor to a bone
  68637. * @param bone The bone that the impostor will be synced to.
  68638. * @param boneMesh The mesh that the bone is influencing.
  68639. * @param jointPivot The pivot of the joint / bone in local space.
  68640. * @param distToJoint Optional distance from the impostor to the joint.
  68641. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  68642. * @param boneAxis Optional vector3 axis the bone is aligned with
  68643. */
  68644. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  68645. var mesh = this.object;
  68646. if (mesh.rotationQuaternion) {
  68647. if (adjustRotation) {
  68648. var tempQuat = PhysicsImpostor._tmpQuat;
  68649. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  68650. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  68651. }
  68652. else {
  68653. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  68654. }
  68655. }
  68656. var pos = PhysicsImpostor._tmpVecs[0];
  68657. var boneDir = PhysicsImpostor._tmpVecs[1];
  68658. if (!boneAxis) {
  68659. boneAxis = PhysicsImpostor._tmpVecs[2];
  68660. boneAxis.x = 0;
  68661. boneAxis.y = 1;
  68662. boneAxis.z = 0;
  68663. }
  68664. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  68665. bone.getAbsolutePositionToRef(boneMesh, pos);
  68666. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  68667. distToJoint = jointPivot.length();
  68668. }
  68669. if (distToJoint !== undefined && distToJoint !== null) {
  68670. pos.x += boneDir.x * distToJoint;
  68671. pos.y += boneDir.y * distToJoint;
  68672. pos.z += boneDir.z * distToJoint;
  68673. }
  68674. mesh.setAbsolutePosition(pos);
  68675. };
  68676. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  68677. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  68678. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68679. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  68680. //Impostor types
  68681. PhysicsImpostor.NoImpostor = 0;
  68682. PhysicsImpostor.SphereImpostor = 1;
  68683. PhysicsImpostor.BoxImpostor = 2;
  68684. PhysicsImpostor.PlaneImpostor = 3;
  68685. PhysicsImpostor.MeshImpostor = 4;
  68686. PhysicsImpostor.CylinderImpostor = 7;
  68687. PhysicsImpostor.ParticleImpostor = 8;
  68688. PhysicsImpostor.HeightmapImpostor = 9;
  68689. return PhysicsImpostor;
  68690. }());
  68691. BABYLON.PhysicsImpostor = PhysicsImpostor;
  68692. })(BABYLON || (BABYLON = {}));
  68693. //# sourceMappingURL=babylon.physicsImpostor.js.map
  68694. var BABYLON;
  68695. (function (BABYLON) {
  68696. var PhysicsEngine = /** @class */ (function () {
  68697. function PhysicsEngine(gravity, _physicsPlugin) {
  68698. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  68699. this._physicsPlugin = _physicsPlugin;
  68700. //new methods and parameters
  68701. this._impostors = [];
  68702. this._joints = [];
  68703. if (!this._physicsPlugin.isSupported()) {
  68704. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  68705. + "Please make sure it is included.");
  68706. }
  68707. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  68708. this.setGravity(gravity);
  68709. this.setTimeStep();
  68710. }
  68711. PhysicsEngine.prototype.setGravity = function (gravity) {
  68712. this.gravity = gravity;
  68713. this._physicsPlugin.setGravity(this.gravity);
  68714. };
  68715. /**
  68716. * Set the time step of the physics engine.
  68717. * default is 1/60.
  68718. * To slow it down, enter 1/600 for example.
  68719. * To speed it up, 1/30
  68720. * @param {number} newTimeStep the new timestep to apply to this world.
  68721. */
  68722. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  68723. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  68724. this._physicsPlugin.setTimeStep(newTimeStep);
  68725. };
  68726. /**
  68727. * Get the time step of the physics engine.
  68728. */
  68729. PhysicsEngine.prototype.getTimeStep = function () {
  68730. return this._physicsPlugin.getTimeStep();
  68731. };
  68732. PhysicsEngine.prototype.dispose = function () {
  68733. this._impostors.forEach(function (impostor) {
  68734. impostor.dispose();
  68735. });
  68736. this._physicsPlugin.dispose();
  68737. };
  68738. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  68739. return this._physicsPlugin.name;
  68740. };
  68741. /**
  68742. * Adding a new impostor for the impostor tracking.
  68743. * This will be done by the impostor itself.
  68744. * @param {PhysicsImpostor} impostor the impostor to add
  68745. */
  68746. PhysicsEngine.prototype.addImpostor = function (impostor) {
  68747. impostor.uniqueId = this._impostors.push(impostor);
  68748. //if no parent, generate the body
  68749. if (!impostor.parent) {
  68750. this._physicsPlugin.generatePhysicsBody(impostor);
  68751. }
  68752. };
  68753. /**
  68754. * Remove an impostor from the engine.
  68755. * This impostor and its mesh will not longer be updated by the physics engine.
  68756. * @param {PhysicsImpostor} impostor the impostor to remove
  68757. */
  68758. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  68759. var index = this._impostors.indexOf(impostor);
  68760. if (index > -1) {
  68761. var removed = this._impostors.splice(index, 1);
  68762. //Is it needed?
  68763. if (removed.length) {
  68764. //this will also remove it from the world.
  68765. removed[0].physicsBody = null;
  68766. }
  68767. }
  68768. };
  68769. /**
  68770. * Add a joint to the physics engine
  68771. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  68772. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  68773. * @param {PhysicsJoint} the joint that will connect both impostors.
  68774. */
  68775. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  68776. var impostorJoint = {
  68777. mainImpostor: mainImpostor,
  68778. connectedImpostor: connectedImpostor,
  68779. joint: joint
  68780. };
  68781. joint.physicsPlugin = this._physicsPlugin;
  68782. this._joints.push(impostorJoint);
  68783. this._physicsPlugin.generateJoint(impostorJoint);
  68784. };
  68785. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  68786. var matchingJoints = this._joints.filter(function (impostorJoint) {
  68787. return (impostorJoint.connectedImpostor === connectedImpostor
  68788. && impostorJoint.joint === joint
  68789. && impostorJoint.mainImpostor === mainImpostor);
  68790. });
  68791. if (matchingJoints.length) {
  68792. this._physicsPlugin.removeJoint(matchingJoints[0]);
  68793. //TODO remove it from the list as well
  68794. }
  68795. };
  68796. /**
  68797. * Called by the scene. no need to call it.
  68798. */
  68799. PhysicsEngine.prototype._step = function (delta) {
  68800. var _this = this;
  68801. //check if any mesh has no body / requires an update
  68802. this._impostors.forEach(function (impostor) {
  68803. if (impostor.isBodyInitRequired()) {
  68804. _this._physicsPlugin.generatePhysicsBody(impostor);
  68805. }
  68806. });
  68807. if (delta > 0.1) {
  68808. delta = 0.1;
  68809. }
  68810. else if (delta <= 0) {
  68811. delta = 1.0 / 60.0;
  68812. }
  68813. this._physicsPlugin.executeStep(delta, this._impostors);
  68814. };
  68815. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  68816. return this._physicsPlugin;
  68817. };
  68818. PhysicsEngine.prototype.getImpostors = function () {
  68819. return this._impostors;
  68820. };
  68821. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  68822. for (var i = 0; i < this._impostors.length; ++i) {
  68823. if (this._impostors[i].object === object) {
  68824. return this._impostors[i];
  68825. }
  68826. }
  68827. return null;
  68828. };
  68829. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  68830. for (var i = 0; i < this._impostors.length; ++i) {
  68831. if (this._impostors[i].physicsBody === body) {
  68832. return this._impostors[i];
  68833. }
  68834. }
  68835. return null;
  68836. };
  68837. // Statics
  68838. PhysicsEngine.Epsilon = 0.001;
  68839. return PhysicsEngine;
  68840. }());
  68841. BABYLON.PhysicsEngine = PhysicsEngine;
  68842. })(BABYLON || (BABYLON = {}));
  68843. //# sourceMappingURL=babylon.physicsEngine.js.map
  68844. var BABYLON;
  68845. (function (BABYLON) {
  68846. var PhysicsHelper = /** @class */ (function () {
  68847. function PhysicsHelper(scene) {
  68848. this._scene = scene;
  68849. this._physicsEngine = this._scene.getPhysicsEngine();
  68850. if (!this._physicsEngine) {
  68851. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  68852. }
  68853. }
  68854. /**
  68855. * @param {Vector3} origin the origin of the explosion
  68856. * @param {number} radius the explosion radius
  68857. * @param {number} strength the explosion strength
  68858. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68859. */
  68860. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  68861. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68862. if (!this._physicsEngine) {
  68863. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  68864. return null;
  68865. }
  68866. var impostors = this._physicsEngine.getImpostors();
  68867. if (impostors.length === 0) {
  68868. return null;
  68869. }
  68870. var event = new PhysicsRadialExplosionEvent(this._scene);
  68871. impostors.forEach(function (impostor) {
  68872. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68873. if (!impostorForceAndContactPoint) {
  68874. return;
  68875. }
  68876. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68877. });
  68878. event.dispose(false);
  68879. return event;
  68880. };
  68881. /**
  68882. * @param {Vector3} origin the origin of the explosion
  68883. * @param {number} radius the explosion radius
  68884. * @param {number} strength the explosion strength
  68885. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68886. */
  68887. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  68888. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68889. if (!this._physicsEngine) {
  68890. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68891. return null;
  68892. }
  68893. var impostors = this._physicsEngine.getImpostors();
  68894. if (impostors.length === 0) {
  68895. return null;
  68896. }
  68897. var event = new PhysicsRadialExplosionEvent(this._scene);
  68898. impostors.forEach(function (impostor) {
  68899. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68900. if (!impostorForceAndContactPoint) {
  68901. return;
  68902. }
  68903. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68904. });
  68905. event.dispose(false);
  68906. return event;
  68907. };
  68908. /**
  68909. * @param {Vector3} origin the origin of the explosion
  68910. * @param {number} radius the explosion radius
  68911. * @param {number} strength the explosion strength
  68912. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68913. */
  68914. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  68915. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68916. if (!this._physicsEngine) {
  68917. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68918. return null;
  68919. }
  68920. var impostors = this._physicsEngine.getImpostors();
  68921. if (impostors.length === 0) {
  68922. return null;
  68923. }
  68924. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  68925. event.dispose(false);
  68926. return event;
  68927. };
  68928. /**
  68929. * @param {Vector3} origin the origin of the updraft
  68930. * @param {number} radius the radius of the updraft
  68931. * @param {number} strength the strength of the updraft
  68932. * @param {number} height the height of the updraft
  68933. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  68934. */
  68935. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  68936. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  68937. if (!this._physicsEngine) {
  68938. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68939. return null;
  68940. }
  68941. if (this._physicsEngine.getImpostors().length === 0) {
  68942. return null;
  68943. }
  68944. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  68945. event.dispose(false);
  68946. return event;
  68947. };
  68948. /**
  68949. * @param {Vector3} origin the of the vortex
  68950. * @param {number} radius the radius of the vortex
  68951. * @param {number} strength the strength of the vortex
  68952. * @param {number} height the height of the vortex
  68953. */
  68954. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  68955. if (!this._physicsEngine) {
  68956. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68957. return null;
  68958. }
  68959. if (this._physicsEngine.getImpostors().length === 0) {
  68960. return null;
  68961. }
  68962. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  68963. event.dispose(false);
  68964. return event;
  68965. };
  68966. return PhysicsHelper;
  68967. }());
  68968. BABYLON.PhysicsHelper = PhysicsHelper;
  68969. /***** Radial explosion *****/
  68970. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  68971. function PhysicsRadialExplosionEvent(scene) {
  68972. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  68973. this._rays = [];
  68974. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  68975. this._scene = scene;
  68976. }
  68977. /**
  68978. * Returns the data related to the radial explosion event (sphere & rays).
  68979. * @returns {PhysicsRadialExplosionEventData}
  68980. */
  68981. PhysicsRadialExplosionEvent.prototype.getData = function () {
  68982. this._dataFetched = true;
  68983. return {
  68984. sphere: this._sphere,
  68985. rays: this._rays,
  68986. };
  68987. };
  68988. /**
  68989. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  68990. * @param impostor
  68991. * @param {Vector3} origin the origin of the explosion
  68992. * @param {number} radius the explosion radius
  68993. * @param {number} strength the explosion strength
  68994. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  68995. * @returns {Nullable<PhysicsForceAndContactPoint>}
  68996. */
  68997. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  68998. if (impostor.mass === 0) {
  68999. return null;
  69000. }
  69001. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  69002. return null;
  69003. }
  69004. if (impostor.object.getClassName() !== 'Mesh') {
  69005. return null;
  69006. }
  69007. var impostorObject = impostor.object;
  69008. var impostorObjectCenter = impostor.getObjectCenter();
  69009. var direction = impostorObjectCenter.subtract(origin);
  69010. var ray = new BABYLON.Ray(origin, direction, radius);
  69011. this._rays.push(ray);
  69012. var hit = ray.intersectsMesh(impostorObject);
  69013. var contactPoint = hit.pickedPoint;
  69014. if (!contactPoint) {
  69015. return null;
  69016. }
  69017. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  69018. if (distanceFromOrigin > radius) {
  69019. return null;
  69020. }
  69021. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  69022. ? strength
  69023. : strength * (1 - (distanceFromOrigin / radius));
  69024. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  69025. return { force: force, contactPoint: contactPoint };
  69026. };
  69027. /**
  69028. * Disposes the sphere.
  69029. * @param {bolean} force
  69030. */
  69031. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  69032. var _this = this;
  69033. if (force === void 0) { force = true; }
  69034. if (force) {
  69035. this._sphere.dispose();
  69036. }
  69037. else {
  69038. setTimeout(function () {
  69039. if (!_this._dataFetched) {
  69040. _this._sphere.dispose();
  69041. }
  69042. }, 0);
  69043. }
  69044. };
  69045. /*** Helpers ***/
  69046. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  69047. if (!this._sphere) {
  69048. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  69049. this._sphere.isVisible = false;
  69050. }
  69051. };
  69052. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  69053. var impostorObject = impostor.object;
  69054. this._prepareSphere();
  69055. this._sphere.position = origin;
  69056. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  69057. this._sphere._updateBoundingInfo();
  69058. this._sphere.computeWorldMatrix(true);
  69059. return this._sphere.intersectsMesh(impostorObject, true);
  69060. };
  69061. return PhysicsRadialExplosionEvent;
  69062. }());
  69063. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  69064. /***** Gravitational Field *****/
  69065. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  69066. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  69067. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  69068. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  69069. this._physicsHelper = physicsHelper;
  69070. this._scene = scene;
  69071. this._origin = origin;
  69072. this._radius = radius;
  69073. this._strength = strength;
  69074. this._falloff = falloff;
  69075. this._tickCallback = this._tick.bind(this);
  69076. }
  69077. /**
  69078. * Returns the data related to the gravitational field event (sphere).
  69079. * @returns {PhysicsGravitationalFieldEventData}
  69080. */
  69081. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  69082. this._dataFetched = true;
  69083. return {
  69084. sphere: this._sphere,
  69085. };
  69086. };
  69087. /**
  69088. * Enables the gravitational field.
  69089. */
  69090. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  69091. this._tickCallback.call(this);
  69092. this._scene.registerBeforeRender(this._tickCallback);
  69093. };
  69094. /**
  69095. * Disables the gravitational field.
  69096. */
  69097. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  69098. this._scene.unregisterBeforeRender(this._tickCallback);
  69099. };
  69100. /**
  69101. * Disposes the sphere.
  69102. * @param {bolean} force
  69103. */
  69104. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  69105. var _this = this;
  69106. if (force === void 0) { force = true; }
  69107. if (force) {
  69108. this._sphere.dispose();
  69109. }
  69110. else {
  69111. setTimeout(function () {
  69112. if (!_this._dataFetched) {
  69113. _this._sphere.dispose();
  69114. }
  69115. }, 0);
  69116. }
  69117. };
  69118. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  69119. // Since the params won't change, we fetch the event only once
  69120. if (this._sphere) {
  69121. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  69122. }
  69123. else {
  69124. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  69125. if (radialExplosionEvent) {
  69126. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  69127. }
  69128. }
  69129. };
  69130. return PhysicsGravitationalFieldEvent;
  69131. }());
  69132. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  69133. /***** Updraft *****/
  69134. var PhysicsUpdraftEvent = /** @class */ (function () {
  69135. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  69136. this._scene = _scene;
  69137. this._origin = _origin;
  69138. this._radius = _radius;
  69139. this._strength = _strength;
  69140. this._height = _height;
  69141. this._updraftMode = _updraftMode;
  69142. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  69143. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  69144. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  69145. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  69146. this._physicsEngine = this._scene.getPhysicsEngine();
  69147. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  69148. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  69149. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  69150. this._originDirection = this._origin.subtract(this._originTop).normalize();
  69151. }
  69152. this._tickCallback = this._tick.bind(this);
  69153. }
  69154. /**
  69155. * Returns the data related to the updraft event (cylinder).
  69156. * @returns {PhysicsUpdraftEventData}
  69157. */
  69158. PhysicsUpdraftEvent.prototype.getData = function () {
  69159. this._dataFetched = true;
  69160. return {
  69161. cylinder: this._cylinder,
  69162. };
  69163. };
  69164. /**
  69165. * Enables the updraft.
  69166. */
  69167. PhysicsUpdraftEvent.prototype.enable = function () {
  69168. this._tickCallback.call(this);
  69169. this._scene.registerBeforeRender(this._tickCallback);
  69170. };
  69171. /**
  69172. * Disables the cortex.
  69173. */
  69174. PhysicsUpdraftEvent.prototype.disable = function () {
  69175. this._scene.unregisterBeforeRender(this._tickCallback);
  69176. };
  69177. /**
  69178. * Disposes the sphere.
  69179. * @param {bolean} force
  69180. */
  69181. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  69182. var _this = this;
  69183. if (force === void 0) { force = true; }
  69184. if (force) {
  69185. this._cylinder.dispose();
  69186. }
  69187. else {
  69188. setTimeout(function () {
  69189. if (!_this._dataFetched) {
  69190. _this._cylinder.dispose();
  69191. }
  69192. }, 0);
  69193. }
  69194. };
  69195. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  69196. if (impostor.mass === 0) {
  69197. return null;
  69198. }
  69199. if (!this._intersectsWithCylinder(impostor)) {
  69200. return null;
  69201. }
  69202. var impostorObjectCenter = impostor.getObjectCenter();
  69203. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  69204. var direction = this._originDirection;
  69205. }
  69206. else {
  69207. var direction = impostorObjectCenter.subtract(this._originTop);
  69208. }
  69209. var multiplier = this._strength * -1;
  69210. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  69211. return { force: force, contactPoint: impostorObjectCenter };
  69212. };
  69213. PhysicsUpdraftEvent.prototype._tick = function () {
  69214. var _this = this;
  69215. this._physicsEngine.getImpostors().forEach(function (impostor) {
  69216. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  69217. if (!impostorForceAndContactPoint) {
  69218. return;
  69219. }
  69220. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  69221. });
  69222. };
  69223. /*** Helpers ***/
  69224. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  69225. if (!this._cylinder) {
  69226. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  69227. height: this._height,
  69228. diameter: this._radius * 2,
  69229. }, this._scene);
  69230. this._cylinder.isVisible = false;
  69231. }
  69232. };
  69233. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  69234. var impostorObject = impostor.object;
  69235. this._prepareCylinder();
  69236. this._cylinder.position = this._cylinderPosition;
  69237. return this._cylinder.intersectsMesh(impostorObject, true);
  69238. };
  69239. return PhysicsUpdraftEvent;
  69240. }());
  69241. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  69242. /***** Vortex *****/
  69243. var PhysicsVortexEvent = /** @class */ (function () {
  69244. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  69245. this._scene = _scene;
  69246. this._origin = _origin;
  69247. this._radius = _radius;
  69248. this._strength = _strength;
  69249. this._height = _height;
  69250. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  69251. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  69252. this._updraftMultiplier = 0.02;
  69253. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  69254. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  69255. this._physicsEngine = this._scene.getPhysicsEngine();
  69256. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  69257. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  69258. this._tickCallback = this._tick.bind(this);
  69259. }
  69260. /**
  69261. * Returns the data related to the vortex event (cylinder).
  69262. * @returns {PhysicsVortexEventData}
  69263. */
  69264. PhysicsVortexEvent.prototype.getData = function () {
  69265. this._dataFetched = true;
  69266. return {
  69267. cylinder: this._cylinder,
  69268. };
  69269. };
  69270. /**
  69271. * Enables the vortex.
  69272. */
  69273. PhysicsVortexEvent.prototype.enable = function () {
  69274. this._tickCallback.call(this);
  69275. this._scene.registerBeforeRender(this._tickCallback);
  69276. };
  69277. /**
  69278. * Disables the cortex.
  69279. */
  69280. PhysicsVortexEvent.prototype.disable = function () {
  69281. this._scene.unregisterBeforeRender(this._tickCallback);
  69282. };
  69283. /**
  69284. * Disposes the sphere.
  69285. * @param {bolean} force
  69286. */
  69287. PhysicsVortexEvent.prototype.dispose = function (force) {
  69288. var _this = this;
  69289. if (force === void 0) { force = true; }
  69290. if (force) {
  69291. this._cylinder.dispose();
  69292. }
  69293. else {
  69294. setTimeout(function () {
  69295. if (!_this._dataFetched) {
  69296. _this._cylinder.dispose();
  69297. }
  69298. }, 0);
  69299. }
  69300. };
  69301. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  69302. if (impostor.mass === 0) {
  69303. return null;
  69304. }
  69305. if (!this._intersectsWithCylinder(impostor)) {
  69306. return null;
  69307. }
  69308. if (impostor.object.getClassName() !== 'Mesh') {
  69309. return null;
  69310. }
  69311. var impostorObject = impostor.object;
  69312. var impostorObjectCenter = impostor.getObjectCenter();
  69313. var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
  69314. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  69315. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  69316. var hit = ray.intersectsMesh(impostorObject);
  69317. var contactPoint = hit.pickedPoint;
  69318. if (!contactPoint) {
  69319. return null;
  69320. }
  69321. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  69322. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  69323. var directionToOrigin = contactPoint.normalize();
  69324. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  69325. directionToOrigin = directionToOrigin.negate();
  69326. }
  69327. // TODO: find a more physically based solution
  69328. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  69329. var forceX = directionToOrigin.x * this._strength / 8;
  69330. var forceY = directionToOrigin.y * this._updraftMultiplier;
  69331. var forceZ = directionToOrigin.z * this._strength / 8;
  69332. }
  69333. else {
  69334. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  69335. var forceY = this._originTop.y * this._updraftMultiplier;
  69336. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  69337. }
  69338. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  69339. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  69340. return { force: force, contactPoint: impostorObjectCenter };
  69341. };
  69342. PhysicsVortexEvent.prototype._tick = function () {
  69343. var _this = this;
  69344. this._physicsEngine.getImpostors().forEach(function (impostor) {
  69345. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  69346. if (!impostorForceAndContactPoint) {
  69347. return;
  69348. }
  69349. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  69350. });
  69351. };
  69352. /*** Helpers ***/
  69353. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  69354. if (!this._cylinder) {
  69355. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  69356. height: this._height,
  69357. diameter: this._radius * 2,
  69358. }, this._scene);
  69359. this._cylinder.isVisible = false;
  69360. }
  69361. };
  69362. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  69363. var impostorObject = impostor.object;
  69364. this._prepareCylinder();
  69365. this._cylinder.position = this._cylinderPosition;
  69366. return this._cylinder.intersectsMesh(impostorObject, true);
  69367. };
  69368. return PhysicsVortexEvent;
  69369. }());
  69370. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  69371. /***** Enums *****/
  69372. /**
  69373. * The strenght of the force in correspondence to the distance of the affected object
  69374. */
  69375. var PhysicsRadialImpulseFalloff;
  69376. (function (PhysicsRadialImpulseFalloff) {
  69377. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  69378. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  69379. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  69380. /**
  69381. * The strenght of the force in correspondence to the distance of the affected object
  69382. */
  69383. var PhysicsUpdraftMode;
  69384. (function (PhysicsUpdraftMode) {
  69385. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  69386. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  69387. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  69388. })(BABYLON || (BABYLON = {}));
  69389. //# sourceMappingURL=babylon.physicsHelper.js.map
  69390. var BABYLON;
  69391. (function (BABYLON) {
  69392. var CannonJSPlugin = /** @class */ (function () {
  69393. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  69394. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  69395. if (iterations === void 0) { iterations = 10; }
  69396. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  69397. this.name = "CannonJSPlugin";
  69398. this._physicsMaterials = new Array();
  69399. this._fixedTimeStep = 1 / 60;
  69400. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  69401. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  69402. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  69403. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  69404. this._tmpPosition = BABYLON.Vector3.Zero();
  69405. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  69406. this._tmpUnityRotation = new BABYLON.Quaternion();
  69407. if (!this.isSupported()) {
  69408. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  69409. return;
  69410. }
  69411. this._extendNamespace();
  69412. this.world = new this.BJSCANNON.World();
  69413. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  69414. this.world.solver.iterations = iterations;
  69415. }
  69416. CannonJSPlugin.prototype.setGravity = function (gravity) {
  69417. this.world.gravity.copy(gravity);
  69418. };
  69419. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  69420. this._fixedTimeStep = timeStep;
  69421. };
  69422. CannonJSPlugin.prototype.getTimeStep = function () {
  69423. return this._fixedTimeStep;
  69424. };
  69425. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  69426. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  69427. };
  69428. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  69429. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  69430. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  69431. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  69432. };
  69433. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  69434. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  69435. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  69436. impostor.physicsBody.applyForce(impulse, worldPoint);
  69437. };
  69438. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  69439. //parent-child relationship. Does this impostor has a parent impostor?
  69440. if (impostor.parent) {
  69441. if (impostor.physicsBody) {
  69442. this.removePhysicsBody(impostor);
  69443. //TODO is that needed?
  69444. impostor.forceUpdate();
  69445. }
  69446. return;
  69447. }
  69448. //should a new body be created for this impostor?
  69449. if (impostor.isBodyInitRequired()) {
  69450. var shape = this._createShape(impostor);
  69451. //unregister events, if body is being changed
  69452. var oldBody = impostor.physicsBody;
  69453. if (oldBody) {
  69454. this.removePhysicsBody(impostor);
  69455. }
  69456. //create the body and material
  69457. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  69458. var bodyCreationObject = {
  69459. mass: impostor.getParam("mass"),
  69460. material: material
  69461. };
  69462. // A simple extend, in case native options were used.
  69463. var nativeOptions = impostor.getParam("nativeOptions");
  69464. for (var key in nativeOptions) {
  69465. if (nativeOptions.hasOwnProperty(key)) {
  69466. bodyCreationObject[key] = nativeOptions[key];
  69467. }
  69468. }
  69469. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  69470. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  69471. this.world.addEventListener("preStep", impostor.beforeStep);
  69472. this.world.addEventListener("postStep", impostor.afterStep);
  69473. impostor.physicsBody.addShape(shape);
  69474. this.world.add(impostor.physicsBody);
  69475. //try to keep the body moving in the right direction by taking old properties.
  69476. //Should be tested!
  69477. if (oldBody) {
  69478. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  69479. impostor.physicsBody[param].copy(oldBody[param]);
  69480. });
  69481. }
  69482. this._processChildMeshes(impostor);
  69483. }
  69484. //now update the body's transformation
  69485. this._updatePhysicsBodyTransformation(impostor);
  69486. };
  69487. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  69488. var _this = this;
  69489. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  69490. var currentRotation = mainImpostor.object.rotationQuaternion;
  69491. if (meshChildren.length) {
  69492. var processMesh = function (localPosition, mesh) {
  69493. if (!currentRotation || !mesh.rotationQuaternion) {
  69494. return;
  69495. }
  69496. var childImpostor = mesh.getPhysicsImpostor();
  69497. if (childImpostor) {
  69498. var parent = childImpostor.parent;
  69499. if (parent !== mainImpostor) {
  69500. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  69501. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  69502. if (childImpostor.physicsBody) {
  69503. _this.removePhysicsBody(childImpostor);
  69504. childImpostor.physicsBody = null;
  69505. }
  69506. childImpostor.parent = mainImpostor;
  69507. childImpostor.resetUpdateFlags();
  69508. 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));
  69509. //Add the mass of the children.
  69510. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  69511. }
  69512. }
  69513. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  69514. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  69515. };
  69516. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  69517. }
  69518. };
  69519. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  69520. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  69521. this.world.removeEventListener("preStep", impostor.beforeStep);
  69522. this.world.removeEventListener("postStep", impostor.afterStep);
  69523. this.world.remove(impostor.physicsBody);
  69524. };
  69525. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  69526. var mainBody = impostorJoint.mainImpostor.physicsBody;
  69527. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  69528. if (!mainBody || !connectedBody) {
  69529. return;
  69530. }
  69531. var constraint;
  69532. var jointData = impostorJoint.joint.jointData;
  69533. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  69534. var constraintData = {
  69535. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  69536. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  69537. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  69538. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  69539. maxForce: jointData.nativeParams.maxForce,
  69540. collideConnected: !!jointData.collision
  69541. };
  69542. switch (impostorJoint.joint.type) {
  69543. case BABYLON.PhysicsJoint.HingeJoint:
  69544. case BABYLON.PhysicsJoint.Hinge2Joint:
  69545. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  69546. break;
  69547. case BABYLON.PhysicsJoint.DistanceJoint:
  69548. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  69549. break;
  69550. case BABYLON.PhysicsJoint.SpringJoint:
  69551. var springData = jointData;
  69552. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  69553. restLength: springData.length,
  69554. stiffness: springData.stiffness,
  69555. damping: springData.damping,
  69556. localAnchorA: constraintData.pivotA,
  69557. localAnchorB: constraintData.pivotB
  69558. });
  69559. break;
  69560. case BABYLON.PhysicsJoint.LockJoint:
  69561. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  69562. break;
  69563. case BABYLON.PhysicsJoint.PointToPointJoint:
  69564. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  69565. default:
  69566. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  69567. break;
  69568. }
  69569. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  69570. constraint.collideConnected = !!jointData.collision;
  69571. impostorJoint.joint.physicsJoint = constraint;
  69572. //don't add spring as constraint, as it is not one.
  69573. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  69574. this.world.addConstraint(constraint);
  69575. }
  69576. else {
  69577. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  69578. constraint.applyForce();
  69579. });
  69580. }
  69581. };
  69582. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  69583. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  69584. };
  69585. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  69586. var index;
  69587. var mat;
  69588. for (index = 0; index < this._physicsMaterials.length; index++) {
  69589. mat = this._physicsMaterials[index];
  69590. if (mat.friction === friction && mat.restitution === restitution) {
  69591. return mat;
  69592. }
  69593. }
  69594. var currentMat = new this.BJSCANNON.Material(name);
  69595. currentMat.friction = friction;
  69596. currentMat.restitution = restitution;
  69597. this._physicsMaterials.push(currentMat);
  69598. return currentMat;
  69599. };
  69600. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  69601. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  69602. };
  69603. CannonJSPlugin.prototype._createShape = function (impostor) {
  69604. var object = impostor.object;
  69605. var returnValue;
  69606. var extendSize = impostor.getObjectExtendSize();
  69607. switch (impostor.type) {
  69608. case BABYLON.PhysicsImpostor.SphereImpostor:
  69609. var radiusX = extendSize.x;
  69610. var radiusY = extendSize.y;
  69611. var radiusZ = extendSize.z;
  69612. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  69613. break;
  69614. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  69615. case BABYLON.PhysicsImpostor.CylinderImpostor:
  69616. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  69617. break;
  69618. case BABYLON.PhysicsImpostor.BoxImpostor:
  69619. var box = extendSize.scale(0.5);
  69620. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  69621. break;
  69622. case BABYLON.PhysicsImpostor.PlaneImpostor:
  69623. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  69624. returnValue = new this.BJSCANNON.Plane();
  69625. break;
  69626. case BABYLON.PhysicsImpostor.MeshImpostor:
  69627. // should transform the vertex data to world coordinates!!
  69628. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  69629. var rawFaces = object.getIndices ? object.getIndices() : [];
  69630. if (!rawVerts)
  69631. return;
  69632. // get only scale! so the object could transform correctly.
  69633. var oldPosition = object.position.clone();
  69634. var oldRotation = object.rotation && object.rotation.clone();
  69635. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  69636. object.position.copyFromFloats(0, 0, 0);
  69637. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  69638. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  69639. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  69640. var transform = object.computeWorldMatrix(true);
  69641. // convert rawVerts to object space
  69642. var temp = new Array();
  69643. var index;
  69644. for (index = 0; index < rawVerts.length; index += 3) {
  69645. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  69646. }
  69647. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  69648. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  69649. //now set back the transformation!
  69650. object.position.copyFrom(oldPosition);
  69651. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  69652. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  69653. break;
  69654. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  69655. var oldPosition2 = object.position.clone();
  69656. var oldRotation2 = object.rotation && object.rotation.clone();
  69657. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  69658. object.position.copyFromFloats(0, 0, 0);
  69659. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  69660. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  69661. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  69662. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  69663. returnValue = this._createHeightmap(object);
  69664. object.position.copyFrom(oldPosition2);
  69665. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  69666. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  69667. object.computeWorldMatrix(true);
  69668. break;
  69669. case BABYLON.PhysicsImpostor.ParticleImpostor:
  69670. returnValue = new this.BJSCANNON.Particle();
  69671. break;
  69672. }
  69673. return returnValue;
  69674. };
  69675. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  69676. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  69677. var transform = object.computeWorldMatrix(true);
  69678. // convert rawVerts to object space
  69679. var temp = new Array();
  69680. var index;
  69681. for (index = 0; index < pos.length; index += 3) {
  69682. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  69683. }
  69684. pos = temp;
  69685. var matrix = new Array();
  69686. //For now pointDepth will not be used and will be automatically calculated.
  69687. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  69688. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  69689. var boundingInfo = object.getBoundingInfo();
  69690. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  69691. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  69692. var elementSize = dim * 2 / arraySize;
  69693. for (var i = 0; i < pos.length; i = i + 3) {
  69694. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  69695. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  69696. var y = -pos[i + 2] + minY;
  69697. if (!matrix[x]) {
  69698. matrix[x] = [];
  69699. }
  69700. if (!matrix[x][z]) {
  69701. matrix[x][z] = y;
  69702. }
  69703. matrix[x][z] = Math.max(y, matrix[x][z]);
  69704. }
  69705. for (var x = 0; x <= arraySize; ++x) {
  69706. if (!matrix[x]) {
  69707. var loc = 1;
  69708. while (!matrix[(x + loc) % arraySize]) {
  69709. loc++;
  69710. }
  69711. matrix[x] = matrix[(x + loc) % arraySize].slice();
  69712. //console.log("missing x", x);
  69713. }
  69714. for (var z = 0; z <= arraySize; ++z) {
  69715. if (!matrix[x][z]) {
  69716. var loc = 1;
  69717. var newValue;
  69718. while (newValue === undefined) {
  69719. newValue = matrix[x][(z + loc++) % arraySize];
  69720. }
  69721. matrix[x][z] = newValue;
  69722. }
  69723. }
  69724. }
  69725. var shape = new this.BJSCANNON.Heightfield(matrix, {
  69726. elementSize: elementSize
  69727. });
  69728. //For future reference, needed for body transformation
  69729. shape.minY = minY;
  69730. return shape;
  69731. };
  69732. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  69733. var object = impostor.object;
  69734. //make sure it is updated...
  69735. object.computeWorldMatrix && object.computeWorldMatrix(true);
  69736. // The delta between the mesh position and the mesh bounding box center
  69737. var bInfo = object.getBoundingInfo();
  69738. if (!bInfo)
  69739. return;
  69740. var center = impostor.getObjectCenter();
  69741. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  69742. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  69743. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  69744. this._tmpPosition.copyFrom(center);
  69745. var quaternion = object.rotationQuaternion;
  69746. if (!quaternion) {
  69747. return;
  69748. }
  69749. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  69750. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  69751. //-90 DEG in X, precalculated
  69752. quaternion = quaternion.multiply(this._minus90X);
  69753. //Invert! (Precalculated, 90 deg in X)
  69754. //No need to clone. this will never change.
  69755. impostor.setDeltaRotation(this._plus90X);
  69756. }
  69757. //If it is a heightfield, if should be centered.
  69758. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  69759. var mesh = object;
  69760. var boundingInfo = mesh.getBoundingInfo();
  69761. //calculate the correct body position:
  69762. var rotationQuaternion = mesh.rotationQuaternion;
  69763. mesh.rotationQuaternion = this._tmpUnityRotation;
  69764. mesh.computeWorldMatrix(true);
  69765. //get original center with no rotation
  69766. var c = center.clone();
  69767. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  69768. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  69769. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  69770. mesh.setPivotMatrix(p);
  69771. mesh.computeWorldMatrix(true);
  69772. //calculate the translation
  69773. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  69774. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  69775. //add it inverted to the delta
  69776. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  69777. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  69778. //rotation is back
  69779. mesh.rotationQuaternion = rotationQuaternion;
  69780. mesh.setPivotMatrix(oldPivot);
  69781. mesh.computeWorldMatrix(true);
  69782. }
  69783. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  69784. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  69785. //this._tmpPosition.copyFrom(object.position);
  69786. }
  69787. impostor.setDeltaPosition(this._tmpDeltaPosition);
  69788. //Now update the impostor object
  69789. impostor.physicsBody.position.copy(this._tmpPosition);
  69790. impostor.physicsBody.quaternion.copy(quaternion);
  69791. };
  69792. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  69793. impostor.object.position.copyFrom(impostor.physicsBody.position);
  69794. if (impostor.object.rotationQuaternion) {
  69795. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  69796. }
  69797. };
  69798. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  69799. impostor.physicsBody.position.copy(newPosition);
  69800. impostor.physicsBody.quaternion.copy(newRotation);
  69801. };
  69802. CannonJSPlugin.prototype.isSupported = function () {
  69803. return this.BJSCANNON !== undefined;
  69804. };
  69805. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  69806. impostor.physicsBody.velocity.copy(velocity);
  69807. };
  69808. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  69809. impostor.physicsBody.angularVelocity.copy(velocity);
  69810. };
  69811. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  69812. var v = impostor.physicsBody.velocity;
  69813. if (!v) {
  69814. return null;
  69815. }
  69816. return new BABYLON.Vector3(v.x, v.y, v.z);
  69817. };
  69818. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  69819. var v = impostor.physicsBody.angularVelocity;
  69820. if (!v) {
  69821. return null;
  69822. }
  69823. return new BABYLON.Vector3(v.x, v.y, v.z);
  69824. };
  69825. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  69826. impostor.physicsBody.mass = mass;
  69827. impostor.physicsBody.updateMassProperties();
  69828. };
  69829. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  69830. return impostor.physicsBody.mass;
  69831. };
  69832. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  69833. return impostor.physicsBody.material.friction;
  69834. };
  69835. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  69836. impostor.physicsBody.material.friction = friction;
  69837. };
  69838. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  69839. return impostor.physicsBody.material.restitution;
  69840. };
  69841. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  69842. impostor.physicsBody.material.restitution = restitution;
  69843. };
  69844. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  69845. impostor.physicsBody.sleep();
  69846. };
  69847. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  69848. impostor.physicsBody.wakeUp();
  69849. };
  69850. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  69851. joint.physicsJoint.distance = maxDistance;
  69852. };
  69853. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  69854. // if (!motorIndex) {
  69855. // joint.physicsJoint.enableMotor();
  69856. // }
  69857. // }
  69858. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  69859. // if (!motorIndex) {
  69860. // joint.physicsJoint.disableMotor();
  69861. // }
  69862. // }
  69863. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  69864. if (!motorIndex) {
  69865. joint.physicsJoint.enableMotor();
  69866. joint.physicsJoint.setMotorSpeed(speed);
  69867. if (maxForce) {
  69868. this.setLimit(joint, maxForce);
  69869. }
  69870. }
  69871. };
  69872. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  69873. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  69874. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  69875. };
  69876. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  69877. var body = impostor.physicsBody;
  69878. mesh.position.x = body.position.x;
  69879. mesh.position.y = body.position.y;
  69880. mesh.position.z = body.position.z;
  69881. if (mesh.rotationQuaternion) {
  69882. mesh.rotationQuaternion.x = body.quaternion.x;
  69883. mesh.rotationQuaternion.y = body.quaternion.y;
  69884. mesh.rotationQuaternion.z = body.quaternion.z;
  69885. mesh.rotationQuaternion.w = body.quaternion.w;
  69886. }
  69887. };
  69888. CannonJSPlugin.prototype.getRadius = function (impostor) {
  69889. var shape = impostor.physicsBody.shapes[0];
  69890. return shape.boundingSphereRadius;
  69891. };
  69892. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  69893. var shape = impostor.physicsBody.shapes[0];
  69894. result.x = shape.halfExtents.x * 2;
  69895. result.y = shape.halfExtents.y * 2;
  69896. result.z = shape.halfExtents.z * 2;
  69897. };
  69898. CannonJSPlugin.prototype.dispose = function () {
  69899. };
  69900. CannonJSPlugin.prototype._extendNamespace = function () {
  69901. //this will force cannon to execute at least one step when using interpolation
  69902. var step_tmp1 = new this.BJSCANNON.Vec3();
  69903. var Engine = this.BJSCANNON;
  69904. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  69905. maxSubSteps = maxSubSteps || 10;
  69906. timeSinceLastCalled = timeSinceLastCalled || 0;
  69907. if (timeSinceLastCalled === 0) {
  69908. this.internalStep(dt);
  69909. this.time += dt;
  69910. }
  69911. else {
  69912. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  69913. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  69914. var t0 = performance.now();
  69915. for (var i = 0; i !== internalSteps; i++) {
  69916. this.internalStep(dt);
  69917. if (performance.now() - t0 > dt * 1000) {
  69918. break;
  69919. }
  69920. }
  69921. this.time += timeSinceLastCalled;
  69922. var h = this.time % dt;
  69923. var h_div_dt = h / dt;
  69924. var interpvelo = step_tmp1;
  69925. var bodies = this.bodies;
  69926. for (var j = 0; j !== bodies.length; j++) {
  69927. var b = bodies[j];
  69928. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  69929. b.position.vsub(b.previousPosition, interpvelo);
  69930. interpvelo.scale(h_div_dt, interpvelo);
  69931. b.position.vadd(interpvelo, b.interpolatedPosition);
  69932. }
  69933. else {
  69934. b.interpolatedPosition.copy(b.position);
  69935. b.interpolatedQuaternion.copy(b.quaternion);
  69936. }
  69937. }
  69938. }
  69939. };
  69940. };
  69941. return CannonJSPlugin;
  69942. }());
  69943. BABYLON.CannonJSPlugin = CannonJSPlugin;
  69944. })(BABYLON || (BABYLON = {}));
  69945. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  69946. var BABYLON;
  69947. (function (BABYLON) {
  69948. var OimoJSPlugin = /** @class */ (function () {
  69949. function OimoJSPlugin(iterations) {
  69950. this.name = "OimoJSPlugin";
  69951. this._tmpImpostorsArray = [];
  69952. this._tmpPositionVector = BABYLON.Vector3.Zero();
  69953. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  69954. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  69955. this.world.worldscale(1);
  69956. this.world.clear();
  69957. //making sure no stats are calculated
  69958. this.world.isNoStat = true;
  69959. }
  69960. OimoJSPlugin.prototype.setGravity = function (gravity) {
  69961. this.world.gravity.copy(gravity);
  69962. };
  69963. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  69964. this.world.timeStep = timeStep;
  69965. };
  69966. OimoJSPlugin.prototype.getTimeStep = function () {
  69967. return this.world.timeStep;
  69968. };
  69969. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  69970. var _this = this;
  69971. impostors.forEach(function (impostor) {
  69972. impostor.beforeStep();
  69973. });
  69974. this.world.step();
  69975. impostors.forEach(function (impostor) {
  69976. impostor.afterStep();
  69977. //update the ordered impostors array
  69978. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  69979. });
  69980. //check for collisions
  69981. var contact = this.world.contacts;
  69982. while (contact !== null) {
  69983. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  69984. contact = contact.next;
  69985. continue;
  69986. }
  69987. //is this body colliding with any other? get the impostor
  69988. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  69989. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  69990. if (!mainImpostor || !collidingImpostor) {
  69991. contact = contact.next;
  69992. continue;
  69993. }
  69994. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  69995. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  69996. contact = contact.next;
  69997. }
  69998. };
  69999. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  70000. var mass = impostor.physicsBody.massInfo.mass;
  70001. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  70002. };
  70003. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  70004. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  70005. this.applyImpulse(impostor, force, contactPoint);
  70006. };
  70007. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  70008. var _this = this;
  70009. //parent-child relationship. Does this impostor has a parent impostor?
  70010. if (impostor.parent) {
  70011. if (impostor.physicsBody) {
  70012. this.removePhysicsBody(impostor);
  70013. //TODO is that needed?
  70014. impostor.forceUpdate();
  70015. }
  70016. return;
  70017. }
  70018. if (impostor.isBodyInitRequired()) {
  70019. var bodyConfig = {
  70020. name: impostor.uniqueId,
  70021. //Oimo must have mass, also for static objects.
  70022. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  70023. size: [],
  70024. type: [],
  70025. pos: [],
  70026. rot: [],
  70027. move: impostor.getParam("mass") !== 0,
  70028. //Supporting older versions of Oimo
  70029. world: this.world
  70030. };
  70031. var impostors = [impostor];
  70032. var addToArray = function (parent) {
  70033. if (!parent.getChildMeshes)
  70034. return;
  70035. parent.getChildMeshes().forEach(function (m) {
  70036. if (m.physicsImpostor) {
  70037. impostors.push(m.physicsImpostor);
  70038. //m.physicsImpostor._init();
  70039. }
  70040. });
  70041. };
  70042. addToArray(impostor.object);
  70043. var checkWithEpsilon_1 = function (value) {
  70044. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  70045. };
  70046. impostors.forEach(function (i) {
  70047. if (!impostor.object.rotationQuaternion) {
  70048. return;
  70049. }
  70050. //get the correct bounding box
  70051. var oldQuaternion = i.object.rotationQuaternion;
  70052. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  70053. x: impostor.object.rotationQuaternion.x,
  70054. y: impostor.object.rotationQuaternion.y,
  70055. z: impostor.object.rotationQuaternion.z,
  70056. s: impostor.object.rotationQuaternion.w
  70057. });
  70058. var extendSize = i.getObjectExtendSize();
  70059. if (i === impostor) {
  70060. var center = impostor.getObjectCenter();
  70061. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  70062. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  70063. //Can also use Array.prototype.push.apply
  70064. bodyConfig.pos.push(center.x);
  70065. bodyConfig.pos.push(center.y);
  70066. bodyConfig.pos.push(center.z);
  70067. //tmp solution
  70068. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  70069. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  70070. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  70071. }
  70072. else {
  70073. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  70074. bodyConfig.pos.push(localPosition.x);
  70075. bodyConfig.pos.push(localPosition.y);
  70076. bodyConfig.pos.push(localPosition.z);
  70077. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  70078. bodyConfig.rot.push(0);
  70079. bodyConfig.rot.push(0);
  70080. bodyConfig.rot.push(0);
  70081. }
  70082. // register mesh
  70083. switch (i.type) {
  70084. case BABYLON.PhysicsImpostor.ParticleImpostor:
  70085. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  70086. case BABYLON.PhysicsImpostor.SphereImpostor:
  70087. var radiusX = extendSize.x;
  70088. var radiusY = extendSize.y;
  70089. var radiusZ = extendSize.z;
  70090. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  70091. bodyConfig.type.push('sphere');
  70092. //due to the way oimo works with compounds, add 3 times
  70093. bodyConfig.size.push(size);
  70094. bodyConfig.size.push(size);
  70095. bodyConfig.size.push(size);
  70096. break;
  70097. case BABYLON.PhysicsImpostor.CylinderImpostor:
  70098. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  70099. var sizeY = checkWithEpsilon_1(extendSize.y);
  70100. bodyConfig.type.push('cylinder');
  70101. bodyConfig.size.push(sizeX);
  70102. bodyConfig.size.push(sizeY);
  70103. //due to the way oimo works with compounds, add one more value.
  70104. bodyConfig.size.push(sizeY);
  70105. break;
  70106. case BABYLON.PhysicsImpostor.PlaneImpostor:
  70107. case BABYLON.PhysicsImpostor.BoxImpostor:
  70108. default:
  70109. var sizeX = checkWithEpsilon_1(extendSize.x);
  70110. var sizeY = checkWithEpsilon_1(extendSize.y);
  70111. var sizeZ = checkWithEpsilon_1(extendSize.z);
  70112. bodyConfig.type.push('box');
  70113. bodyConfig.size.push(sizeX);
  70114. bodyConfig.size.push(sizeY);
  70115. bodyConfig.size.push(sizeZ);
  70116. break;
  70117. }
  70118. //actually not needed, but hey...
  70119. i.object.rotationQuaternion = oldQuaternion;
  70120. });
  70121. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  70122. }
  70123. else {
  70124. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  70125. }
  70126. impostor.setDeltaPosition(this._tmpPositionVector);
  70127. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  70128. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  70129. };
  70130. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  70131. //impostor.physicsBody.dispose();
  70132. //Same as : (older oimo versions)
  70133. this.world.removeRigidBody(impostor.physicsBody);
  70134. };
  70135. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  70136. var mainBody = impostorJoint.mainImpostor.physicsBody;
  70137. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  70138. if (!mainBody || !connectedBody) {
  70139. return;
  70140. }
  70141. var jointData = impostorJoint.joint.jointData;
  70142. var options = jointData.nativeParams || {};
  70143. var type;
  70144. var nativeJointData = {
  70145. body1: mainBody,
  70146. body2: connectedBody,
  70147. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  70148. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  70149. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  70150. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  70151. min: options.min,
  70152. max: options.max,
  70153. collision: options.collision || jointData.collision,
  70154. spring: options.spring,
  70155. //supporting older version of Oimo
  70156. world: this.world
  70157. };
  70158. switch (impostorJoint.joint.type) {
  70159. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  70160. type = "jointBall";
  70161. break;
  70162. case BABYLON.PhysicsJoint.SpringJoint:
  70163. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  70164. var springData = jointData;
  70165. nativeJointData.min = springData.length || nativeJointData.min;
  70166. //Max should also be set, just make sure it is at least min
  70167. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  70168. case BABYLON.PhysicsJoint.DistanceJoint:
  70169. type = "jointDistance";
  70170. nativeJointData.max = jointData.maxDistance;
  70171. break;
  70172. case BABYLON.PhysicsJoint.PrismaticJoint:
  70173. type = "jointPrisme";
  70174. break;
  70175. case BABYLON.PhysicsJoint.SliderJoint:
  70176. type = "jointSlide";
  70177. break;
  70178. case BABYLON.PhysicsJoint.WheelJoint:
  70179. type = "jointWheel";
  70180. break;
  70181. case BABYLON.PhysicsJoint.HingeJoint:
  70182. default:
  70183. type = "jointHinge";
  70184. break;
  70185. }
  70186. nativeJointData.type = type;
  70187. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  70188. };
  70189. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  70190. //Bug in Oimo prevents us from disposing a joint in the playground
  70191. //joint.joint.physicsJoint.dispose();
  70192. //So we will bruteforce it!
  70193. try {
  70194. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  70195. }
  70196. catch (e) {
  70197. BABYLON.Tools.Warn(e);
  70198. }
  70199. };
  70200. OimoJSPlugin.prototype.isSupported = function () {
  70201. return this.BJSOIMO !== undefined;
  70202. };
  70203. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  70204. if (!impostor.physicsBody.sleeping) {
  70205. //TODO check that
  70206. if (impostor.physicsBody.shapes.next) {
  70207. var parentShape = this._getLastShape(impostor.physicsBody);
  70208. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  70209. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  70210. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  70211. }
  70212. else {
  70213. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  70214. }
  70215. if (impostor.object.rotationQuaternion) {
  70216. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  70217. impostor.object.rotationQuaternion.normalize();
  70218. }
  70219. }
  70220. };
  70221. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  70222. var body = impostor.physicsBody;
  70223. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  70224. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  70225. body.syncShapes();
  70226. body.awake();
  70227. };
  70228. OimoJSPlugin.prototype._getLastShape = function (body) {
  70229. var lastShape = body.shapes;
  70230. while (lastShape.next) {
  70231. lastShape = lastShape.next;
  70232. }
  70233. return lastShape;
  70234. };
  70235. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  70236. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  70237. };
  70238. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  70239. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  70240. };
  70241. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  70242. var v = impostor.physicsBody.linearVelocity;
  70243. if (!v) {
  70244. return null;
  70245. }
  70246. return new BABYLON.Vector3(v.x, v.y, v.z);
  70247. };
  70248. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  70249. var v = impostor.physicsBody.angularVelocity;
  70250. if (!v) {
  70251. return null;
  70252. }
  70253. return new BABYLON.Vector3(v.x, v.y, v.z);
  70254. };
  70255. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  70256. var staticBody = mass === 0;
  70257. //this will actually set the body's density and not its mass.
  70258. //But this is how oimo treats the mass variable.
  70259. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  70260. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  70261. };
  70262. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  70263. return impostor.physicsBody.shapes.density;
  70264. };
  70265. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  70266. return impostor.physicsBody.shapes.friction;
  70267. };
  70268. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  70269. impostor.physicsBody.shapes.friction = friction;
  70270. };
  70271. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  70272. return impostor.physicsBody.shapes.restitution;
  70273. };
  70274. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  70275. impostor.physicsBody.shapes.restitution = restitution;
  70276. };
  70277. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  70278. impostor.physicsBody.sleep();
  70279. };
  70280. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  70281. impostor.physicsBody.awake();
  70282. };
  70283. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  70284. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  70285. if (minDistance !== void 0) {
  70286. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  70287. }
  70288. };
  70289. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  70290. //TODO separate rotational and transational motors.
  70291. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  70292. if (motor) {
  70293. motor.setMotor(speed, maxForce);
  70294. }
  70295. };
  70296. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  70297. //TODO separate rotational and transational motors.
  70298. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  70299. if (motor) {
  70300. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  70301. }
  70302. };
  70303. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  70304. var body = impostor.physicsBody;
  70305. mesh.position.x = body.position.x;
  70306. mesh.position.y = body.position.y;
  70307. mesh.position.z = body.position.z;
  70308. if (mesh.rotationQuaternion) {
  70309. mesh.rotationQuaternion.x = body.orientation.x;
  70310. mesh.rotationQuaternion.y = body.orientation.y;
  70311. mesh.rotationQuaternion.z = body.orientation.z;
  70312. mesh.rotationQuaternion.w = body.orientation.s;
  70313. }
  70314. };
  70315. OimoJSPlugin.prototype.getRadius = function (impostor) {
  70316. return impostor.physicsBody.shapes.radius;
  70317. };
  70318. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  70319. var shape = impostor.physicsBody.shapes;
  70320. result.x = shape.halfWidth * 2;
  70321. result.y = shape.halfHeight * 2;
  70322. result.z = shape.halfDepth * 2;
  70323. };
  70324. OimoJSPlugin.prototype.dispose = function () {
  70325. this.world.clear();
  70326. };
  70327. return OimoJSPlugin;
  70328. }());
  70329. BABYLON.OimoJSPlugin = OimoJSPlugin;
  70330. })(BABYLON || (BABYLON = {}));
  70331. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  70332. var BABYLON;
  70333. (function (BABYLON) {
  70334. /*
  70335. * Based on jsTGALoader - Javascript loader for TGA file
  70336. * By Vincent Thibault
  70337. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  70338. */
  70339. var TGATools = /** @class */ (function () {
  70340. function TGATools() {
  70341. }
  70342. TGATools.GetTGAHeader = function (data) {
  70343. var offset = 0;
  70344. var header = {
  70345. id_length: data[offset++],
  70346. colormap_type: data[offset++],
  70347. image_type: data[offset++],
  70348. colormap_index: data[offset++] | data[offset++] << 8,
  70349. colormap_length: data[offset++] | data[offset++] << 8,
  70350. colormap_size: data[offset++],
  70351. origin: [
  70352. data[offset++] | data[offset++] << 8,
  70353. data[offset++] | data[offset++] << 8
  70354. ],
  70355. width: data[offset++] | data[offset++] << 8,
  70356. height: data[offset++] | data[offset++] << 8,
  70357. pixel_size: data[offset++],
  70358. flags: data[offset++]
  70359. };
  70360. return header;
  70361. };
  70362. TGATools.UploadContent = function (gl, data) {
  70363. // Not enough data to contain header ?
  70364. if (data.length < 19) {
  70365. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  70366. return;
  70367. }
  70368. // Read Header
  70369. var offset = 18;
  70370. var header = TGATools.GetTGAHeader(data);
  70371. // Assume it's a valid Targa file.
  70372. if (header.id_length + offset > data.length) {
  70373. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  70374. return;
  70375. }
  70376. // Skip not needed data
  70377. offset += header.id_length;
  70378. var use_rle = false;
  70379. var use_pal = false;
  70380. var use_grey = false;
  70381. // Get some informations.
  70382. switch (header.image_type) {
  70383. case TGATools._TYPE_RLE_INDEXED:
  70384. use_rle = true;
  70385. case TGATools._TYPE_INDEXED:
  70386. use_pal = true;
  70387. break;
  70388. case TGATools._TYPE_RLE_RGB:
  70389. use_rle = true;
  70390. case TGATools._TYPE_RGB:
  70391. // use_rgb = true;
  70392. break;
  70393. case TGATools._TYPE_RLE_GREY:
  70394. use_rle = true;
  70395. case TGATools._TYPE_GREY:
  70396. use_grey = true;
  70397. break;
  70398. }
  70399. var pixel_data;
  70400. // var numAlphaBits = header.flags & 0xf;
  70401. var pixel_size = header.pixel_size >> 3;
  70402. var pixel_total = header.width * header.height * pixel_size;
  70403. // Read palettes
  70404. var palettes;
  70405. if (use_pal) {
  70406. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  70407. }
  70408. // Read LRE
  70409. if (use_rle) {
  70410. pixel_data = new Uint8Array(pixel_total);
  70411. var c, count, i;
  70412. var localOffset = 0;
  70413. var pixels = new Uint8Array(pixel_size);
  70414. while (offset < pixel_total && localOffset < pixel_total) {
  70415. c = data[offset++];
  70416. count = (c & 0x7f) + 1;
  70417. // RLE pixels
  70418. if (c & 0x80) {
  70419. // Bind pixel tmp array
  70420. for (i = 0; i < pixel_size; ++i) {
  70421. pixels[i] = data[offset++];
  70422. }
  70423. // Copy pixel array
  70424. for (i = 0; i < count; ++i) {
  70425. pixel_data.set(pixels, localOffset + i * pixel_size);
  70426. }
  70427. localOffset += pixel_size * count;
  70428. }
  70429. else {
  70430. count *= pixel_size;
  70431. for (i = 0; i < count; ++i) {
  70432. pixel_data[localOffset + i] = data[offset++];
  70433. }
  70434. localOffset += count;
  70435. }
  70436. }
  70437. }
  70438. else {
  70439. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  70440. }
  70441. // Load to texture
  70442. var x_start, y_start, x_step, y_step, y_end, x_end;
  70443. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  70444. default:
  70445. case TGATools._ORIGIN_UL:
  70446. x_start = 0;
  70447. x_step = 1;
  70448. x_end = header.width;
  70449. y_start = 0;
  70450. y_step = 1;
  70451. y_end = header.height;
  70452. break;
  70453. case TGATools._ORIGIN_BL:
  70454. x_start = 0;
  70455. x_step = 1;
  70456. x_end = header.width;
  70457. y_start = header.height - 1;
  70458. y_step = -1;
  70459. y_end = -1;
  70460. break;
  70461. case TGATools._ORIGIN_UR:
  70462. x_start = header.width - 1;
  70463. x_step = -1;
  70464. x_end = -1;
  70465. y_start = 0;
  70466. y_step = 1;
  70467. y_end = header.height;
  70468. break;
  70469. case TGATools._ORIGIN_BR:
  70470. x_start = header.width - 1;
  70471. x_step = -1;
  70472. x_end = -1;
  70473. y_start = header.height - 1;
  70474. y_step = -1;
  70475. y_end = -1;
  70476. break;
  70477. }
  70478. // Load the specify method
  70479. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  70480. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  70481. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  70482. };
  70483. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70484. var image = pixel_data, colormap = palettes;
  70485. var width = header.width, height = header.height;
  70486. var color, i = 0, x, y;
  70487. var imageData = new Uint8Array(width * height * 4);
  70488. for (y = y_start; y !== y_end; y += y_step) {
  70489. for (x = x_start; x !== x_end; x += x_step, i++) {
  70490. color = image[i];
  70491. imageData[(x + width * y) * 4 + 3] = 255;
  70492. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  70493. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  70494. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  70495. }
  70496. }
  70497. return imageData;
  70498. };
  70499. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70500. var image = pixel_data;
  70501. var width = header.width, height = header.height;
  70502. var color, i = 0, x, y;
  70503. var imageData = new Uint8Array(width * height * 4);
  70504. for (y = y_start; y !== y_end; y += y_step) {
  70505. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  70506. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  70507. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  70508. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  70509. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  70510. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  70511. }
  70512. }
  70513. return imageData;
  70514. };
  70515. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70516. var image = pixel_data;
  70517. var width = header.width, height = header.height;
  70518. var i = 0, x, y;
  70519. var imageData = new Uint8Array(width * height * 4);
  70520. for (y = y_start; y !== y_end; y += y_step) {
  70521. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  70522. imageData[(x + width * y) * 4 + 3] = 255;
  70523. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70524. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  70525. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  70526. }
  70527. }
  70528. return imageData;
  70529. };
  70530. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70531. var image = pixel_data;
  70532. var width = header.width, height = header.height;
  70533. var i = 0, x, y;
  70534. var imageData = new Uint8Array(width * height * 4);
  70535. for (y = y_start; y !== y_end; y += y_step) {
  70536. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  70537. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70538. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  70539. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  70540. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  70541. }
  70542. }
  70543. return imageData;
  70544. };
  70545. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70546. var image = pixel_data;
  70547. var width = header.width, height = header.height;
  70548. var color, i = 0, x, y;
  70549. var imageData = new Uint8Array(width * height * 4);
  70550. for (y = y_start; y !== y_end; y += y_step) {
  70551. for (x = x_start; x !== x_end; x += x_step, i++) {
  70552. color = image[i];
  70553. imageData[(x + width * y) * 4 + 0] = color;
  70554. imageData[(x + width * y) * 4 + 1] = color;
  70555. imageData[(x + width * y) * 4 + 2] = color;
  70556. imageData[(x + width * y) * 4 + 3] = 255;
  70557. }
  70558. }
  70559. return imageData;
  70560. };
  70561. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70562. var image = pixel_data;
  70563. var width = header.width, height = header.height;
  70564. var i = 0, x, y;
  70565. var imageData = new Uint8Array(width * height * 4);
  70566. for (y = y_start; y !== y_end; y += y_step) {
  70567. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  70568. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  70569. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  70570. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70571. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  70572. }
  70573. }
  70574. return imageData;
  70575. };
  70576. //private static _TYPE_NO_DATA = 0;
  70577. TGATools._TYPE_INDEXED = 1;
  70578. TGATools._TYPE_RGB = 2;
  70579. TGATools._TYPE_GREY = 3;
  70580. TGATools._TYPE_RLE_INDEXED = 9;
  70581. TGATools._TYPE_RLE_RGB = 10;
  70582. TGATools._TYPE_RLE_GREY = 11;
  70583. TGATools._ORIGIN_MASK = 0x30;
  70584. TGATools._ORIGIN_SHIFT = 0x04;
  70585. TGATools._ORIGIN_BL = 0x00;
  70586. TGATools._ORIGIN_BR = 0x01;
  70587. TGATools._ORIGIN_UL = 0x02;
  70588. TGATools._ORIGIN_UR = 0x03;
  70589. return TGATools;
  70590. }());
  70591. BABYLON.TGATools = TGATools;
  70592. })(BABYLON || (BABYLON = {}));
  70593. //# sourceMappingURL=babylon.tga.js.map
  70594. var BABYLON;
  70595. (function (BABYLON) {
  70596. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  70597. // All values and structures referenced from:
  70598. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  70599. var DDS_MAGIC = 0x20534444;
  70600. var
  70601. //DDSD_CAPS = 0x1,
  70602. //DDSD_HEIGHT = 0x2,
  70603. //DDSD_WIDTH = 0x4,
  70604. //DDSD_PITCH = 0x8,
  70605. //DDSD_PIXELFORMAT = 0x1000,
  70606. DDSD_MIPMAPCOUNT = 0x20000;
  70607. //DDSD_LINEARSIZE = 0x80000,
  70608. //DDSD_DEPTH = 0x800000;
  70609. // var DDSCAPS_COMPLEX = 0x8,
  70610. // DDSCAPS_MIPMAP = 0x400000,
  70611. // DDSCAPS_TEXTURE = 0x1000;
  70612. var DDSCAPS2_CUBEMAP = 0x200;
  70613. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  70614. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  70615. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  70616. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  70617. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  70618. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  70619. // DDSCAPS2_VOLUME = 0x200000;
  70620. var
  70621. //DDPF_ALPHAPIXELS = 0x1,
  70622. //DDPF_ALPHA = 0x2,
  70623. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  70624. //DDPF_YUV = 0x200,
  70625. DDPF_LUMINANCE = 0x20000;
  70626. function FourCCToInt32(value) {
  70627. return value.charCodeAt(0) +
  70628. (value.charCodeAt(1) << 8) +
  70629. (value.charCodeAt(2) << 16) +
  70630. (value.charCodeAt(3) << 24);
  70631. }
  70632. function Int32ToFourCC(value) {
  70633. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  70634. }
  70635. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  70636. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  70637. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  70638. var FOURCC_DX10 = FourCCToInt32("DX10");
  70639. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  70640. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  70641. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  70642. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  70643. var headerLengthInt = 31; // The header length in 32 bit ints
  70644. // Offsets into the header array
  70645. var off_magic = 0;
  70646. var off_size = 1;
  70647. var off_flags = 2;
  70648. var off_height = 3;
  70649. var off_width = 4;
  70650. var off_mipmapCount = 7;
  70651. var off_pfFlags = 20;
  70652. var off_pfFourCC = 21;
  70653. var off_RGBbpp = 22;
  70654. // var off_RMask = 23;
  70655. // var off_GMask = 24;
  70656. // var off_BMask = 25;
  70657. // var off_AMask = 26;
  70658. // var off_caps1 = 27;
  70659. var off_caps2 = 28;
  70660. // var off_caps3 = 29;
  70661. // var off_caps4 = 30;
  70662. var off_dxgiFormat = 32;
  70663. ;
  70664. var DDSTools = /** @class */ (function () {
  70665. function DDSTools() {
  70666. }
  70667. DDSTools.GetDDSInfo = function (arrayBuffer) {
  70668. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70669. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  70670. var mipmapCount = 1;
  70671. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  70672. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70673. }
  70674. var fourCC = header[off_pfFourCC];
  70675. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  70676. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70677. switch (fourCC) {
  70678. case FOURCC_D3DFMT_R16G16B16A16F:
  70679. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70680. break;
  70681. case FOURCC_D3DFMT_R32G32B32A32F:
  70682. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70683. break;
  70684. case FOURCC_DX10:
  70685. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  70686. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70687. break;
  70688. }
  70689. }
  70690. return {
  70691. width: header[off_width],
  70692. height: header[off_height],
  70693. mipmapCount: mipmapCount,
  70694. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  70695. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  70696. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  70697. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  70698. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  70699. dxgiFormat: dxgiFormat,
  70700. textureType: textureType
  70701. };
  70702. };
  70703. DDSTools._ToHalfFloat = function (value) {
  70704. if (!DDSTools._FloatView) {
  70705. DDSTools._FloatView = new Float32Array(1);
  70706. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  70707. }
  70708. DDSTools._FloatView[0] = value;
  70709. var x = DDSTools._Int32View[0];
  70710. var bits = (x >> 16) & 0x8000; /* Get the sign */
  70711. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  70712. var e = (x >> 23) & 0xff; /* Using int is faster here */
  70713. /* If zero, or denormal, or exponent underflows too much for a denormal
  70714. * half, return signed zero. */
  70715. if (e < 103) {
  70716. return bits;
  70717. }
  70718. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  70719. if (e > 142) {
  70720. bits |= 0x7c00;
  70721. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  70722. * not Inf, so make sure we set one mantissa bit too. */
  70723. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  70724. return bits;
  70725. }
  70726. /* If exponent underflows but not too much, return a denormal */
  70727. if (e < 113) {
  70728. m |= 0x0800;
  70729. /* Extra rounding may overflow and set mantissa to 0 and exponent
  70730. * to 1, which is OK. */
  70731. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  70732. return bits;
  70733. }
  70734. bits |= ((e - 112) << 10) | (m >> 1);
  70735. bits += m & 1;
  70736. return bits;
  70737. };
  70738. DDSTools._FromHalfFloat = function (value) {
  70739. var s = (value & 0x8000) >> 15;
  70740. var e = (value & 0x7C00) >> 10;
  70741. var f = value & 0x03FF;
  70742. if (e === 0) {
  70743. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  70744. }
  70745. else if (e == 0x1F) {
  70746. return f ? NaN : ((s ? -1 : 1) * Infinity);
  70747. }
  70748. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  70749. };
  70750. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70751. var destArray = new Float32Array(dataLength);
  70752. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70753. var index = 0;
  70754. for (var y = 0; y < height; y++) {
  70755. for (var x = 0; x < width; x++) {
  70756. var srcPos = (x + y * width) * 4;
  70757. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  70758. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  70759. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  70760. if (DDSTools.StoreLODInAlphaChannel) {
  70761. destArray[index + 3] = lod;
  70762. }
  70763. else {
  70764. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  70765. }
  70766. index += 4;
  70767. }
  70768. }
  70769. return destArray;
  70770. };
  70771. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70772. if (DDSTools.StoreLODInAlphaChannel) {
  70773. var destArray = new Uint16Array(dataLength);
  70774. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70775. var index = 0;
  70776. for (var y = 0; y < height; y++) {
  70777. for (var x = 0; x < width; x++) {
  70778. var srcPos = (x + y * width) * 4;
  70779. destArray[index] = srcData[srcPos];
  70780. destArray[index + 1] = srcData[srcPos + 1];
  70781. destArray[index + 2] = srcData[srcPos + 2];
  70782. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  70783. index += 4;
  70784. }
  70785. }
  70786. return destArray;
  70787. }
  70788. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  70789. };
  70790. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70791. if (DDSTools.StoreLODInAlphaChannel) {
  70792. var destArray = new Float32Array(dataLength);
  70793. var srcData = new Float32Array(arrayBuffer, dataOffset);
  70794. var index = 0;
  70795. for (var y = 0; y < height; y++) {
  70796. for (var x = 0; x < width; x++) {
  70797. var srcPos = (x + y * width) * 4;
  70798. destArray[index] = srcData[srcPos];
  70799. destArray[index + 1] = srcData[srcPos + 1];
  70800. destArray[index + 2] = srcData[srcPos + 2];
  70801. destArray[index + 3] = lod;
  70802. index += 4;
  70803. }
  70804. }
  70805. return destArray;
  70806. }
  70807. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  70808. };
  70809. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70810. var destArray = new Uint8Array(dataLength);
  70811. var srcData = new Float32Array(arrayBuffer, dataOffset);
  70812. var index = 0;
  70813. for (var y = 0; y < height; y++) {
  70814. for (var x = 0; x < width; x++) {
  70815. var srcPos = (x + y * width) * 4;
  70816. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  70817. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  70818. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  70819. if (DDSTools.StoreLODInAlphaChannel) {
  70820. destArray[index + 3] = lod;
  70821. }
  70822. else {
  70823. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  70824. }
  70825. index += 4;
  70826. }
  70827. }
  70828. return destArray;
  70829. };
  70830. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70831. var destArray = new Uint8Array(dataLength);
  70832. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70833. var index = 0;
  70834. for (var y = 0; y < height; y++) {
  70835. for (var x = 0; x < width; x++) {
  70836. var srcPos = (x + y * width) * 4;
  70837. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  70838. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  70839. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  70840. if (DDSTools.StoreLODInAlphaChannel) {
  70841. destArray[index + 3] = lod;
  70842. }
  70843. else {
  70844. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  70845. }
  70846. index += 4;
  70847. }
  70848. }
  70849. return destArray;
  70850. };
  70851. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70852. var byteArray = new Uint8Array(dataLength);
  70853. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70854. var index = 0;
  70855. for (var y = 0; y < height; y++) {
  70856. for (var x = 0; x < width; x++) {
  70857. var srcPos = (x + y * width) * 4;
  70858. byteArray[index] = srcData[srcPos + 2];
  70859. byteArray[index + 1] = srcData[srcPos + 1];
  70860. byteArray[index + 2] = srcData[srcPos];
  70861. byteArray[index + 3] = srcData[srcPos + 3];
  70862. index += 4;
  70863. }
  70864. }
  70865. return byteArray;
  70866. };
  70867. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70868. var byteArray = new Uint8Array(dataLength);
  70869. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70870. var index = 0;
  70871. for (var y = 0; y < height; y++) {
  70872. for (var x = 0; x < width; x++) {
  70873. var srcPos = (x + y * width) * 3;
  70874. byteArray[index] = srcData[srcPos + 2];
  70875. byteArray[index + 1] = srcData[srcPos + 1];
  70876. byteArray[index + 2] = srcData[srcPos];
  70877. index += 3;
  70878. }
  70879. }
  70880. return byteArray;
  70881. };
  70882. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70883. var byteArray = new Uint8Array(dataLength);
  70884. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70885. var index = 0;
  70886. for (var y = 0; y < height; y++) {
  70887. for (var x = 0; x < width; x++) {
  70888. var srcPos = (x + y * width);
  70889. byteArray[index] = srcData[srcPos];
  70890. index++;
  70891. }
  70892. }
  70893. return byteArray;
  70894. };
  70895. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  70896. if (lodIndex === void 0) { lodIndex = -1; }
  70897. var ext = engine.getCaps().s3tc;
  70898. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70899. var fourCC, width, height, dataLength = 0, dataOffset;
  70900. var byteArray, mipmapCount, mip;
  70901. var internalFormat = 0;
  70902. var format = 0;
  70903. var blockBytes = 1;
  70904. if (header[off_magic] !== DDS_MAGIC) {
  70905. BABYLON.Tools.Error("Invalid magic number in DDS header");
  70906. return;
  70907. }
  70908. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  70909. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  70910. return;
  70911. }
  70912. if (info.isCompressed && !ext) {
  70913. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  70914. return;
  70915. }
  70916. var bpp = header[off_RGBbpp];
  70917. dataOffset = header[off_size] + 4;
  70918. var computeFormats = false;
  70919. if (info.isFourCC) {
  70920. fourCC = header[off_pfFourCC];
  70921. switch (fourCC) {
  70922. case FOURCC_DXT1:
  70923. blockBytes = 8;
  70924. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  70925. break;
  70926. case FOURCC_DXT3:
  70927. blockBytes = 16;
  70928. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  70929. break;
  70930. case FOURCC_DXT5:
  70931. blockBytes = 16;
  70932. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  70933. break;
  70934. case FOURCC_D3DFMT_R16G16B16A16F:
  70935. computeFormats = true;
  70936. break;
  70937. case FOURCC_D3DFMT_R32G32B32A32F:
  70938. computeFormats = true;
  70939. break;
  70940. case FOURCC_DX10:
  70941. // There is an additionnal header so dataOffset need to be changed
  70942. dataOffset += 5 * 4; // 5 uints
  70943. var supported = false;
  70944. switch (info.dxgiFormat) {
  70945. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  70946. computeFormats = true;
  70947. supported = true;
  70948. break;
  70949. case DXGI_FORMAT_B8G8R8X8_UNORM:
  70950. info.isRGB = true;
  70951. info.isFourCC = false;
  70952. bpp = 32;
  70953. supported = true;
  70954. break;
  70955. }
  70956. if (supported) {
  70957. break;
  70958. }
  70959. default:
  70960. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  70961. return;
  70962. }
  70963. }
  70964. if (computeFormats) {
  70965. format = engine._getWebGLTextureType(info.textureType);
  70966. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70967. }
  70968. mipmapCount = 1;
  70969. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  70970. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70971. }
  70972. for (var face = 0; face < faces; face++) {
  70973. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  70974. width = header[off_width];
  70975. height = header[off_height];
  70976. for (mip = 0; mip < mipmapCount; ++mip) {
  70977. if (lodIndex === -1 || lodIndex === mip) {
  70978. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  70979. var i = (lodIndex === -1) ? mip : 0;
  70980. if (!info.isCompressed && info.isFourCC) {
  70981. dataLength = width * height * 4;
  70982. var floatArray = null;
  70983. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  70984. if (bpp === 128) {
  70985. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70986. }
  70987. else if (bpp === 64) {
  70988. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70989. }
  70990. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70991. format = engine._getWebGLTextureType(info.textureType);
  70992. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70993. }
  70994. else {
  70995. if (bpp === 128) {
  70996. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70997. }
  70998. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  70999. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  71000. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  71001. format = engine._getWebGLTextureType(info.textureType);
  71002. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  71003. }
  71004. else {
  71005. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  71006. }
  71007. }
  71008. if (floatArray) {
  71009. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  71010. }
  71011. }
  71012. else if (info.isRGB) {
  71013. if (bpp === 24) {
  71014. dataLength = width * height * 3;
  71015. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  71016. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  71017. }
  71018. else {
  71019. dataLength = width * height * 4;
  71020. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  71021. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  71022. }
  71023. }
  71024. else if (info.isLuminance) {
  71025. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  71026. var unpaddedRowSize = width;
  71027. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  71028. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  71029. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  71030. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  71031. }
  71032. else {
  71033. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  71034. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  71035. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  71036. }
  71037. }
  71038. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  71039. width *= 0.5;
  71040. height *= 0.5;
  71041. width = Math.max(1.0, width);
  71042. height = Math.max(1.0, height);
  71043. }
  71044. if (currentFace !== undefined) {
  71045. // Loading a single face
  71046. break;
  71047. }
  71048. }
  71049. };
  71050. DDSTools.StoreLODInAlphaChannel = false;
  71051. return DDSTools;
  71052. }());
  71053. BABYLON.DDSTools = DDSTools;
  71054. })(BABYLON || (BABYLON = {}));
  71055. //# sourceMappingURL=babylon.dds.js.map
  71056. var BABYLON;
  71057. (function (BABYLON) {
  71058. /**
  71059. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  71060. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  71061. */
  71062. var KhronosTextureContainer = /** @class */ (function () {
  71063. /**
  71064. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  71065. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  71066. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  71067. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  71068. */
  71069. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  71070. this.arrayBuffer = arrayBuffer;
  71071. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  71072. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  71073. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  71074. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  71075. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  71076. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  71077. BABYLON.Tools.Error("texture missing KTX identifier");
  71078. return;
  71079. }
  71080. // load the reset of the header in native 32 bit int
  71081. var header = new Int32Array(this.arrayBuffer, 12, 13);
  71082. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  71083. var oppositeEndianess = header[0] === 0x01020304;
  71084. // read all the header elements in order they exist in the file, without modification (sans endainness)
  71085. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  71086. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  71087. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  71088. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  71089. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  71090. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  71091. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  71092. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  71093. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  71094. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  71095. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  71096. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  71097. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  71098. if (this.glType !== 0) {
  71099. BABYLON.Tools.Error("only compressed formats currently supported");
  71100. return;
  71101. }
  71102. else {
  71103. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  71104. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  71105. }
  71106. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  71107. BABYLON.Tools.Error("only 2D textures currently supported");
  71108. return;
  71109. }
  71110. if (this.numberOfArrayElements !== 0) {
  71111. BABYLON.Tools.Error("texture arrays not currently supported");
  71112. return;
  71113. }
  71114. if (this.numberOfFaces !== facesExpected) {
  71115. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  71116. return;
  71117. }
  71118. // we now have a completely validated file, so could use existence of loadType as success
  71119. // would need to make this more elaborate & adjust checks above to support more than one load type
  71120. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  71121. }
  71122. // not as fast hardware based, but will probably never need to use
  71123. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  71124. return ((val & 0xFF) << 24)
  71125. | ((val & 0xFF00) << 8)
  71126. | ((val >> 8) & 0xFF00)
  71127. | ((val >> 24) & 0xFF);
  71128. };
  71129. /**
  71130. * It is assumed that the texture has already been created & is currently bound
  71131. */
  71132. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  71133. switch (this.loadType) {
  71134. case KhronosTextureContainer.COMPRESSED_2D:
  71135. this._upload2DCompressedLevels(gl, loadMipmaps);
  71136. break;
  71137. case KhronosTextureContainer.TEX_2D:
  71138. case KhronosTextureContainer.COMPRESSED_3D:
  71139. case KhronosTextureContainer.TEX_3D:
  71140. }
  71141. };
  71142. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  71143. // initialize width & height for level 1
  71144. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  71145. var width = this.pixelWidth;
  71146. var height = this.pixelHeight;
  71147. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  71148. for (var level = 0; level < mipmapCount; level++) {
  71149. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  71150. for (var face = 0; face < this.numberOfFaces; face++) {
  71151. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  71152. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  71153. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  71154. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  71155. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  71156. }
  71157. width = Math.max(1.0, width * 0.5);
  71158. height = Math.max(1.0, height * 0.5);
  71159. }
  71160. };
  71161. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  71162. // load types
  71163. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  71164. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  71165. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  71166. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  71167. return KhronosTextureContainer;
  71168. }());
  71169. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  71170. })(BABYLON || (BABYLON = {}));
  71171. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  71172. var BABYLON;
  71173. (function (BABYLON) {
  71174. var Debug = /** @class */ (function () {
  71175. function Debug() {
  71176. }
  71177. Debug.AxesViewer = /** @class */ (function () {
  71178. function AxesViewer(scene, scaleLines) {
  71179. if (scaleLines === void 0) { scaleLines = 1; }
  71180. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71181. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71182. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71183. this.scaleLines = 1;
  71184. this.scaleLines = scaleLines;
  71185. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  71186. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  71187. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  71188. this._xmesh.renderingGroupId = 2;
  71189. this._ymesh.renderingGroupId = 2;
  71190. this._zmesh.renderingGroupId = 2;
  71191. this._xmesh.material.checkReadyOnlyOnce = true;
  71192. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  71193. this._ymesh.material.checkReadyOnlyOnce = true;
  71194. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  71195. this._zmesh.material.checkReadyOnlyOnce = true;
  71196. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  71197. this.scene = scene;
  71198. }
  71199. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  71200. var scaleLines = this.scaleLines;
  71201. if (this._xmesh) {
  71202. this._xmesh.position.copyFrom(position);
  71203. }
  71204. if (this._ymesh) {
  71205. this._ymesh.position.copyFrom(position);
  71206. }
  71207. if (this._zmesh) {
  71208. this._zmesh.position.copyFrom(position);
  71209. }
  71210. var point2 = this._xline[1];
  71211. point2.x = xaxis.x * scaleLines;
  71212. point2.y = xaxis.y * scaleLines;
  71213. point2.z = xaxis.z * scaleLines;
  71214. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  71215. point2 = this._yline[1];
  71216. point2.x = yaxis.x * scaleLines;
  71217. point2.y = yaxis.y * scaleLines;
  71218. point2.z = yaxis.z * scaleLines;
  71219. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  71220. point2 = this._zline[1];
  71221. point2.x = zaxis.x * scaleLines;
  71222. point2.y = zaxis.y * scaleLines;
  71223. point2.z = zaxis.z * scaleLines;
  71224. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  71225. };
  71226. AxesViewer.prototype.dispose = function () {
  71227. if (this._xmesh) {
  71228. this._xmesh.dispose();
  71229. }
  71230. if (this._ymesh) {
  71231. this._ymesh.dispose();
  71232. }
  71233. if (this._zmesh) {
  71234. this._zmesh.dispose();
  71235. }
  71236. this._xmesh = null;
  71237. this._ymesh = null;
  71238. this._zmesh = null;
  71239. this.scene = null;
  71240. };
  71241. return AxesViewer;
  71242. }());
  71243. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  71244. __extends(BoneAxesViewer, _super);
  71245. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  71246. if (scaleLines === void 0) { scaleLines = 1; }
  71247. var _this = _super.call(this, scene, scaleLines) || this;
  71248. _this.pos = BABYLON.Vector3.Zero();
  71249. _this.xaxis = BABYLON.Vector3.Zero();
  71250. _this.yaxis = BABYLON.Vector3.Zero();
  71251. _this.zaxis = BABYLON.Vector3.Zero();
  71252. _this.mesh = mesh;
  71253. _this.bone = bone;
  71254. return _this;
  71255. }
  71256. BoneAxesViewer.prototype.update = function () {
  71257. if (!this.mesh || !this.bone) {
  71258. return;
  71259. }
  71260. var bone = this.bone;
  71261. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  71262. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  71263. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  71264. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  71265. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  71266. };
  71267. BoneAxesViewer.prototype.dispose = function () {
  71268. if (this.mesh) {
  71269. this.mesh = null;
  71270. this.bone = null;
  71271. _super.prototype.dispose.call(this);
  71272. }
  71273. };
  71274. return BoneAxesViewer;
  71275. }(Debug.AxesViewer));
  71276. Debug.PhysicsViewer = /** @class */ (function () {
  71277. function PhysicsViewer(scene) {
  71278. this._impostors = [];
  71279. this._meshes = [];
  71280. this._numMeshes = 0;
  71281. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71282. var physicEngine = this._scene.getPhysicsEngine();
  71283. if (physicEngine) {
  71284. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  71285. }
  71286. }
  71287. PhysicsViewer.prototype._updateDebugMeshes = function () {
  71288. var plugin = this._physicsEnginePlugin;
  71289. for (var i = 0; i < this._numMeshes; i++) {
  71290. var impostor = this._impostors[i];
  71291. if (!impostor) {
  71292. continue;
  71293. }
  71294. if (impostor.isDisposed) {
  71295. this.hideImpostor(this._impostors[i--]);
  71296. }
  71297. else {
  71298. var mesh = this._meshes[i];
  71299. if (mesh && plugin) {
  71300. plugin.syncMeshWithImpostor(mesh, impostor);
  71301. }
  71302. }
  71303. }
  71304. };
  71305. PhysicsViewer.prototype.showImpostor = function (impostor) {
  71306. if (!this._scene) {
  71307. return;
  71308. }
  71309. for (var i = 0; i < this._numMeshes; i++) {
  71310. if (this._impostors[i] == impostor) {
  71311. return;
  71312. }
  71313. }
  71314. var debugMesh = this._getDebugMesh(impostor, this._scene);
  71315. if (debugMesh) {
  71316. this._impostors[this._numMeshes] = impostor;
  71317. this._meshes[this._numMeshes] = debugMesh;
  71318. if (this._numMeshes === 0) {
  71319. this._renderFunction = this._updateDebugMeshes.bind(this);
  71320. this._scene.registerBeforeRender(this._renderFunction);
  71321. }
  71322. this._numMeshes++;
  71323. }
  71324. };
  71325. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  71326. if (!impostor || !this._scene) {
  71327. return;
  71328. }
  71329. var removed = false;
  71330. for (var i = 0; i < this._numMeshes; i++) {
  71331. if (this._impostors[i] == impostor) {
  71332. var mesh = this._meshes[i];
  71333. if (!mesh) {
  71334. continue;
  71335. }
  71336. this._scene.removeMesh(mesh);
  71337. mesh.dispose();
  71338. this._numMeshes--;
  71339. if (this._numMeshes > 0) {
  71340. this._meshes[i] = this._meshes[this._numMeshes];
  71341. this._impostors[i] = this._impostors[this._numMeshes];
  71342. this._meshes[this._numMeshes] = null;
  71343. this._impostors[this._numMeshes] = null;
  71344. }
  71345. else {
  71346. this._meshes[0] = null;
  71347. this._impostors[0] = null;
  71348. }
  71349. removed = true;
  71350. break;
  71351. }
  71352. }
  71353. if (removed && this._numMeshes === 0) {
  71354. this._scene.unregisterBeforeRender(this._renderFunction);
  71355. }
  71356. };
  71357. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  71358. if (!this._debugMaterial) {
  71359. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  71360. this._debugMaterial.wireframe = true;
  71361. }
  71362. return this._debugMaterial;
  71363. };
  71364. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  71365. if (!this._debugBoxMesh) {
  71366. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  71367. this._debugBoxMesh.renderingGroupId = 1;
  71368. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  71369. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  71370. scene.removeMesh(this._debugBoxMesh);
  71371. }
  71372. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  71373. };
  71374. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  71375. if (!this._debugSphereMesh) {
  71376. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  71377. this._debugSphereMesh.renderingGroupId = 1;
  71378. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  71379. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  71380. scene.removeMesh(this._debugSphereMesh);
  71381. }
  71382. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  71383. };
  71384. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  71385. var mesh = null;
  71386. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  71387. mesh = this._getDebugBoxMesh(scene);
  71388. impostor.getBoxSizeToRef(mesh.scaling);
  71389. }
  71390. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  71391. mesh = this._getDebugSphereMesh(scene);
  71392. var radius = impostor.getRadius();
  71393. mesh.scaling.x = radius * 2;
  71394. mesh.scaling.y = radius * 2;
  71395. mesh.scaling.z = radius * 2;
  71396. }
  71397. return mesh;
  71398. };
  71399. PhysicsViewer.prototype.dispose = function () {
  71400. for (var i = 0; i < this._numMeshes; i++) {
  71401. this.hideImpostor(this._impostors[i]);
  71402. }
  71403. if (this._debugBoxMesh) {
  71404. this._debugBoxMesh.dispose();
  71405. }
  71406. if (this._debugSphereMesh) {
  71407. this._debugSphereMesh.dispose();
  71408. }
  71409. if (this._debugMaterial) {
  71410. this._debugMaterial.dispose();
  71411. }
  71412. this._impostors.length = 0;
  71413. this._scene = null;
  71414. this._physicsEnginePlugin = null;
  71415. };
  71416. return PhysicsViewer;
  71417. }());
  71418. Debug.SkeletonViewer = /** @class */ (function () {
  71419. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  71420. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  71421. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  71422. this.skeleton = skeleton;
  71423. this.mesh = mesh;
  71424. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  71425. this.renderingGroupId = renderingGroupId;
  71426. this.color = BABYLON.Color3.White();
  71427. this._debugLines = new Array();
  71428. this._isEnabled = false;
  71429. this._scene = scene;
  71430. this.update();
  71431. this._renderFunction = this.update.bind(this);
  71432. }
  71433. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  71434. get: function () {
  71435. return this._isEnabled;
  71436. },
  71437. set: function (value) {
  71438. if (this._isEnabled === value) {
  71439. return;
  71440. }
  71441. this._isEnabled = value;
  71442. if (value) {
  71443. this._scene.registerBeforeRender(this._renderFunction);
  71444. }
  71445. else {
  71446. this._scene.unregisterBeforeRender(this._renderFunction);
  71447. }
  71448. },
  71449. enumerable: true,
  71450. configurable: true
  71451. });
  71452. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  71453. if (x === void 0) { x = 0; }
  71454. if (y === void 0) { y = 0; }
  71455. if (z === void 0) { z = 0; }
  71456. var tmat = BABYLON.Tmp.Matrix[0];
  71457. var parentBone = bone.getParent();
  71458. tmat.copyFrom(bone.getLocalMatrix());
  71459. if (x !== 0 || y !== 0 || z !== 0) {
  71460. var tmat2 = BABYLON.Tmp.Matrix[1];
  71461. BABYLON.Matrix.IdentityToRef(tmat2);
  71462. tmat2.m[12] = x;
  71463. tmat2.m[13] = y;
  71464. tmat2.m[14] = z;
  71465. tmat2.multiplyToRef(tmat, tmat);
  71466. }
  71467. if (parentBone) {
  71468. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  71469. }
  71470. tmat.multiplyToRef(meshMat, tmat);
  71471. position.x = tmat.m[12];
  71472. position.y = tmat.m[13];
  71473. position.z = tmat.m[14];
  71474. };
  71475. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  71476. var len = bones.length;
  71477. var meshPos = this.mesh.position;
  71478. for (var i = 0; i < len; i++) {
  71479. var bone = bones[i];
  71480. var points = this._debugLines[i];
  71481. if (!points) {
  71482. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71483. this._debugLines[i] = points;
  71484. }
  71485. this._getBonePosition(points[0], bone, meshMat);
  71486. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  71487. points[0].subtractInPlace(meshPos);
  71488. points[1].subtractInPlace(meshPos);
  71489. }
  71490. };
  71491. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  71492. var len = bones.length;
  71493. var boneNum = 0;
  71494. var meshPos = this.mesh.position;
  71495. for (var i = len - 1; i >= 0; i--) {
  71496. var childBone = bones[i];
  71497. var parentBone = childBone.getParent();
  71498. if (!parentBone) {
  71499. continue;
  71500. }
  71501. var points = this._debugLines[boneNum];
  71502. if (!points) {
  71503. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71504. this._debugLines[boneNum] = points;
  71505. }
  71506. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  71507. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  71508. points[0].subtractInPlace(meshPos);
  71509. points[1].subtractInPlace(meshPos);
  71510. boneNum++;
  71511. }
  71512. };
  71513. SkeletonViewer.prototype.update = function () {
  71514. if (this.autoUpdateBonesMatrices) {
  71515. this.skeleton.computeAbsoluteTransforms();
  71516. }
  71517. if (this.skeleton.bones[0].length === undefined) {
  71518. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  71519. }
  71520. else {
  71521. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  71522. }
  71523. if (!this._debugMesh) {
  71524. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  71525. this._debugMesh.renderingGroupId = this.renderingGroupId;
  71526. }
  71527. else {
  71528. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  71529. }
  71530. this._debugMesh.position.copyFrom(this.mesh.position);
  71531. this._debugMesh.color = this.color;
  71532. };
  71533. SkeletonViewer.prototype.dispose = function () {
  71534. if (this._debugMesh) {
  71535. this.isEnabled = false;
  71536. this._debugMesh.dispose();
  71537. this._debugMesh = null;
  71538. }
  71539. };
  71540. return SkeletonViewer;
  71541. }());
  71542. return Debug;
  71543. }());
  71544. BABYLON.Debug = Debug;
  71545. })(BABYLON || (BABYLON = {}));
  71546. //# sourceMappingURL=babylon.debugModules.js.map
  71547. var BABYLON;
  71548. (function (BABYLON) {
  71549. var RayHelper = /** @class */ (function () {
  71550. function RayHelper(ray) {
  71551. this.ray = ray;
  71552. }
  71553. RayHelper.CreateAndShow = function (ray, scene, color) {
  71554. var helper = new RayHelper(ray);
  71555. helper.show(scene, color);
  71556. return helper;
  71557. };
  71558. RayHelper.prototype.show = function (scene, color) {
  71559. if (!this._renderFunction && this.ray) {
  71560. var ray = this.ray;
  71561. this._renderFunction = this._render.bind(this);
  71562. this._scene = scene;
  71563. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  71564. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  71565. if (this._renderFunction) {
  71566. this._scene.registerBeforeRender(this._renderFunction);
  71567. }
  71568. }
  71569. if (color && this._renderLine) {
  71570. this._renderLine.color.copyFrom(color);
  71571. }
  71572. };
  71573. RayHelper.prototype.hide = function () {
  71574. if (this._renderFunction && this._scene) {
  71575. this._scene.unregisterBeforeRender(this._renderFunction);
  71576. this._scene = null;
  71577. this._renderFunction = null;
  71578. if (this._renderLine) {
  71579. this._renderLine.dispose();
  71580. this._renderLine = null;
  71581. }
  71582. this._renderPoints = [];
  71583. }
  71584. };
  71585. RayHelper.prototype._render = function () {
  71586. var ray = this.ray;
  71587. if (!ray) {
  71588. return;
  71589. }
  71590. var point = this._renderPoints[1];
  71591. var len = Math.min(ray.length, 1000000);
  71592. point.copyFrom(ray.direction);
  71593. point.scaleInPlace(len);
  71594. point.addInPlace(ray.origin);
  71595. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  71596. };
  71597. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  71598. this._attachedToMesh = mesh;
  71599. var ray = this.ray;
  71600. if (!ray) {
  71601. return;
  71602. }
  71603. if (!ray.direction) {
  71604. ray.direction = BABYLON.Vector3.Zero();
  71605. }
  71606. if (!ray.origin) {
  71607. ray.origin = BABYLON.Vector3.Zero();
  71608. }
  71609. if (length) {
  71610. ray.length = length;
  71611. }
  71612. if (!meshSpaceOrigin) {
  71613. meshSpaceOrigin = BABYLON.Vector3.Zero();
  71614. }
  71615. if (!meshSpaceDirection) {
  71616. // -1 so that this will work with Mesh.lookAt
  71617. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  71618. }
  71619. if (!this._meshSpaceDirection) {
  71620. this._meshSpaceDirection = meshSpaceDirection.clone();
  71621. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  71622. }
  71623. else {
  71624. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  71625. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  71626. }
  71627. if (!this._updateToMeshFunction) {
  71628. this._updateToMeshFunction = this._updateToMesh.bind(this);
  71629. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  71630. }
  71631. this._updateToMesh();
  71632. };
  71633. RayHelper.prototype.detachFromMesh = function () {
  71634. if (this._attachedToMesh) {
  71635. if (this._updateToMeshFunction) {
  71636. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  71637. }
  71638. this._attachedToMesh = null;
  71639. this._updateToMeshFunction = null;
  71640. }
  71641. };
  71642. RayHelper.prototype._updateToMesh = function () {
  71643. var ray = this.ray;
  71644. if (!this._attachedToMesh || !ray) {
  71645. return;
  71646. }
  71647. if (this._attachedToMesh._isDisposed) {
  71648. this.detachFromMesh();
  71649. return;
  71650. }
  71651. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  71652. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  71653. };
  71654. RayHelper.prototype.dispose = function () {
  71655. this.hide();
  71656. this.detachFromMesh();
  71657. this.ray = null;
  71658. };
  71659. return RayHelper;
  71660. }());
  71661. BABYLON.RayHelper = RayHelper;
  71662. })(BABYLON || (BABYLON = {}));
  71663. //# sourceMappingURL=babylon.rayHelper.js.map
  71664. var BABYLON;
  71665. (function (BABYLON) {
  71666. // load the inspector using require, if not present in the global namespace.
  71667. var DebugLayer = /** @class */ (function () {
  71668. function DebugLayer(scene) {
  71669. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  71670. this._scene = scene;
  71671. // load inspector using require, if it doesn't exist on the global namespace.
  71672. }
  71673. /** Creates the inspector window. */
  71674. DebugLayer.prototype._createInspector = function (config) {
  71675. if (config === void 0) { config = {}; }
  71676. var popup = config.popup || false;
  71677. var initialTab = config.initialTab || 0;
  71678. var parentElement = config.parentElement || null;
  71679. if (!this._inspector) {
  71680. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  71681. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  71682. } // else nothing to do,; instance is already existing
  71683. };
  71684. DebugLayer.prototype.isVisible = function () {
  71685. if (!this._inspector) {
  71686. return false;
  71687. }
  71688. return true;
  71689. };
  71690. DebugLayer.prototype.hide = function () {
  71691. if (this._inspector) {
  71692. try {
  71693. this._inspector.dispose();
  71694. }
  71695. catch (e) {
  71696. // If the inspector has been removed directly from the inspector tool
  71697. }
  71698. this._inspector = null;
  71699. }
  71700. };
  71701. DebugLayer.prototype.show = function (config) {
  71702. if (config === void 0) { config = {}; }
  71703. if (typeof this.BJSINSPECTOR == 'undefined') {
  71704. // Load inspector and add it to the DOM
  71705. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  71706. }
  71707. else {
  71708. // Otherwise creates the inspector
  71709. this._createInspector(config);
  71710. }
  71711. };
  71712. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  71713. return DebugLayer;
  71714. }());
  71715. BABYLON.DebugLayer = DebugLayer;
  71716. })(BABYLON || (BABYLON = {}));
  71717. //# sourceMappingURL=babylon.debugLayer.js.map
  71718. var BABYLON;
  71719. (function (BABYLON) {
  71720. var BoundingBoxRenderer = /** @class */ (function () {
  71721. function BoundingBoxRenderer(scene) {
  71722. this.frontColor = new BABYLON.Color3(1, 1, 1);
  71723. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  71724. this.showBackLines = true;
  71725. this.renderList = new BABYLON.SmartArray(32);
  71726. this._vertexBuffers = {};
  71727. this._scene = scene;
  71728. }
  71729. BoundingBoxRenderer.prototype._prepareRessources = function () {
  71730. if (this._colorShader) {
  71731. return;
  71732. }
  71733. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  71734. attributes: [BABYLON.VertexBuffer.PositionKind],
  71735. uniforms: ["world", "viewProjection", "color"]
  71736. });
  71737. var engine = this._scene.getEngine();
  71738. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  71739. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  71740. this._createIndexBuffer();
  71741. };
  71742. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  71743. var engine = this._scene.getEngine();
  71744. 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]);
  71745. };
  71746. BoundingBoxRenderer.prototype._rebuild = function () {
  71747. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71748. if (vb) {
  71749. vb._rebuild();
  71750. }
  71751. this._createIndexBuffer();
  71752. };
  71753. BoundingBoxRenderer.prototype.reset = function () {
  71754. this.renderList.reset();
  71755. };
  71756. BoundingBoxRenderer.prototype.render = function () {
  71757. if (this.renderList.length === 0) {
  71758. return;
  71759. }
  71760. this._prepareRessources();
  71761. if (!this._colorShader.isReady()) {
  71762. return;
  71763. }
  71764. var engine = this._scene.getEngine();
  71765. engine.setDepthWrite(false);
  71766. this._colorShader._preBind();
  71767. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  71768. var boundingBox = this.renderList.data[boundingBoxIndex];
  71769. var min = boundingBox.minimum;
  71770. var max = boundingBox.maximum;
  71771. var diff = max.subtract(min);
  71772. var median = min.add(diff.scale(0.5));
  71773. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  71774. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  71775. .multiply(boundingBox.getWorldMatrix());
  71776. // VBOs
  71777. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  71778. if (this.showBackLines) {
  71779. // Back
  71780. engine.setDepthFunctionToGreaterOrEqual();
  71781. this._scene.resetCachedMaterial();
  71782. this._colorShader.setColor4("color", this.backColor.toColor4());
  71783. this._colorShader.bind(worldMatrix);
  71784. // Draw order
  71785. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  71786. }
  71787. // Front
  71788. engine.setDepthFunctionToLess();
  71789. this._scene.resetCachedMaterial();
  71790. this._colorShader.setColor4("color", this.frontColor.toColor4());
  71791. this._colorShader.bind(worldMatrix);
  71792. // Draw order
  71793. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  71794. }
  71795. this._colorShader.unbind();
  71796. engine.setDepthFunctionToLessOrEqual();
  71797. engine.setDepthWrite(true);
  71798. };
  71799. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  71800. this._prepareRessources();
  71801. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  71802. return;
  71803. }
  71804. var engine = this._scene.getEngine();
  71805. engine.setDepthWrite(false);
  71806. engine.setColorWrite(false);
  71807. this._colorShader._preBind();
  71808. var boundingBox = mesh._boundingInfo.boundingBox;
  71809. var min = boundingBox.minimum;
  71810. var max = boundingBox.maximum;
  71811. var diff = max.subtract(min);
  71812. var median = min.add(diff.scale(0.5));
  71813. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  71814. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  71815. .multiply(boundingBox.getWorldMatrix());
  71816. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  71817. engine.setDepthFunctionToLess();
  71818. this._scene.resetCachedMaterial();
  71819. this._colorShader.bind(worldMatrix);
  71820. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 24);
  71821. this._colorShader.unbind();
  71822. engine.setDepthFunctionToLessOrEqual();
  71823. engine.setDepthWrite(true);
  71824. engine.setColorWrite(true);
  71825. };
  71826. BoundingBoxRenderer.prototype.dispose = function () {
  71827. if (!this._colorShader) {
  71828. return;
  71829. }
  71830. this.renderList.dispose();
  71831. this._colorShader.dispose();
  71832. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71833. if (buffer) {
  71834. buffer.dispose();
  71835. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71836. }
  71837. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71838. };
  71839. return BoundingBoxRenderer;
  71840. }());
  71841. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  71842. })(BABYLON || (BABYLON = {}));
  71843. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  71844. var BABYLON;
  71845. (function (BABYLON) {
  71846. var MorphTarget = /** @class */ (function () {
  71847. function MorphTarget(name, influence) {
  71848. if (influence === void 0) { influence = 0; }
  71849. this.name = name;
  71850. this.animations = new Array();
  71851. this._positions = null;
  71852. this._normals = null;
  71853. this._tangents = null;
  71854. this.onInfluenceChanged = new BABYLON.Observable();
  71855. this.influence = influence;
  71856. }
  71857. Object.defineProperty(MorphTarget.prototype, "influence", {
  71858. get: function () {
  71859. return this._influence;
  71860. },
  71861. set: function (influence) {
  71862. if (this._influence === influence) {
  71863. return;
  71864. }
  71865. var previous = this._influence;
  71866. this._influence = influence;
  71867. if (this.onInfluenceChanged.hasObservers) {
  71868. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  71869. }
  71870. },
  71871. enumerable: true,
  71872. configurable: true
  71873. });
  71874. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  71875. get: function () {
  71876. return !!this._positions;
  71877. },
  71878. enumerable: true,
  71879. configurable: true
  71880. });
  71881. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  71882. get: function () {
  71883. return !!this._normals;
  71884. },
  71885. enumerable: true,
  71886. configurable: true
  71887. });
  71888. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  71889. get: function () {
  71890. return !!this._tangents;
  71891. },
  71892. enumerable: true,
  71893. configurable: true
  71894. });
  71895. MorphTarget.prototype.setPositions = function (data) {
  71896. this._positions = data;
  71897. };
  71898. MorphTarget.prototype.getPositions = function () {
  71899. return this._positions;
  71900. };
  71901. MorphTarget.prototype.setNormals = function (data) {
  71902. this._normals = data;
  71903. };
  71904. MorphTarget.prototype.getNormals = function () {
  71905. return this._normals;
  71906. };
  71907. MorphTarget.prototype.setTangents = function (data) {
  71908. this._tangents = data;
  71909. };
  71910. MorphTarget.prototype.getTangents = function () {
  71911. return this._tangents;
  71912. };
  71913. /**
  71914. * Serializes the current target into a Serialization object.
  71915. * Returns the serialized object.
  71916. */
  71917. MorphTarget.prototype.serialize = function () {
  71918. var serializationObject = {};
  71919. serializationObject.name = this.name;
  71920. serializationObject.influence = this.influence;
  71921. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  71922. if (this.hasNormals) {
  71923. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  71924. }
  71925. if (this.hasTangents) {
  71926. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  71927. }
  71928. // Animations
  71929. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  71930. return serializationObject;
  71931. };
  71932. // Statics
  71933. MorphTarget.Parse = function (serializationObject) {
  71934. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  71935. result.setPositions(serializationObject.positions);
  71936. if (serializationObject.normals) {
  71937. result.setNormals(serializationObject.normals);
  71938. }
  71939. if (serializationObject.tangents) {
  71940. result.setTangents(serializationObject.tangents);
  71941. }
  71942. // Animations
  71943. if (serializationObject.animations) {
  71944. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  71945. var parsedAnimation = serializationObject.animations[animationIndex];
  71946. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  71947. }
  71948. }
  71949. return result;
  71950. };
  71951. MorphTarget.FromMesh = function (mesh, name, influence) {
  71952. if (!name) {
  71953. name = mesh.name;
  71954. }
  71955. var result = new MorphTarget(name, influence);
  71956. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  71957. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  71958. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  71959. }
  71960. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  71961. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  71962. }
  71963. return result;
  71964. };
  71965. return MorphTarget;
  71966. }());
  71967. BABYLON.MorphTarget = MorphTarget;
  71968. })(BABYLON || (BABYLON = {}));
  71969. //# sourceMappingURL=babylon.morphTarget.js.map
  71970. var BABYLON;
  71971. (function (BABYLON) {
  71972. var MorphTargetManager = /** @class */ (function () {
  71973. function MorphTargetManager(scene) {
  71974. if (scene === void 0) { scene = null; }
  71975. this._targets = new Array();
  71976. this._targetObservable = new Array();
  71977. this._activeTargets = new BABYLON.SmartArray(16);
  71978. this._supportsNormals = false;
  71979. this._supportsTangents = false;
  71980. this._vertexCount = 0;
  71981. this._uniqueId = 0;
  71982. this._tempInfluences = new Array();
  71983. if (!scene) {
  71984. scene = BABYLON.Engine.LastCreatedScene;
  71985. }
  71986. this._scene = scene;
  71987. if (this._scene) {
  71988. this._scene.morphTargetManagers.push(this);
  71989. this._uniqueId = this._scene.getUniqueId();
  71990. }
  71991. }
  71992. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  71993. get: function () {
  71994. return this._uniqueId;
  71995. },
  71996. enumerable: true,
  71997. configurable: true
  71998. });
  71999. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  72000. get: function () {
  72001. return this._vertexCount;
  72002. },
  72003. enumerable: true,
  72004. configurable: true
  72005. });
  72006. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  72007. get: function () {
  72008. return this._supportsNormals;
  72009. },
  72010. enumerable: true,
  72011. configurable: true
  72012. });
  72013. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  72014. get: function () {
  72015. return this._supportsTangents;
  72016. },
  72017. enumerable: true,
  72018. configurable: true
  72019. });
  72020. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  72021. get: function () {
  72022. return this._targets.length;
  72023. },
  72024. enumerable: true,
  72025. configurable: true
  72026. });
  72027. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  72028. get: function () {
  72029. return this._activeTargets.length;
  72030. },
  72031. enumerable: true,
  72032. configurable: true
  72033. });
  72034. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  72035. get: function () {
  72036. return this._influences;
  72037. },
  72038. enumerable: true,
  72039. configurable: true
  72040. });
  72041. MorphTargetManager.prototype.getActiveTarget = function (index) {
  72042. return this._activeTargets.data[index];
  72043. };
  72044. MorphTargetManager.prototype.getTarget = function (index) {
  72045. return this._targets[index];
  72046. };
  72047. MorphTargetManager.prototype.addTarget = function (target) {
  72048. var _this = this;
  72049. this._targets.push(target);
  72050. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  72051. _this._syncActiveTargets(needUpdate);
  72052. }));
  72053. this._syncActiveTargets(true);
  72054. };
  72055. MorphTargetManager.prototype.removeTarget = function (target) {
  72056. var index = this._targets.indexOf(target);
  72057. if (index >= 0) {
  72058. this._targets.splice(index, 1);
  72059. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  72060. this._syncActiveTargets(true);
  72061. }
  72062. };
  72063. /**
  72064. * Serializes the current manager into a Serialization object.
  72065. * Returns the serialized object.
  72066. */
  72067. MorphTargetManager.prototype.serialize = function () {
  72068. var serializationObject = {};
  72069. serializationObject.id = this.uniqueId;
  72070. serializationObject.targets = [];
  72071. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  72072. var target = _a[_i];
  72073. serializationObject.targets.push(target.serialize());
  72074. }
  72075. return serializationObject;
  72076. };
  72077. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  72078. var influenceCount = 0;
  72079. this._activeTargets.reset();
  72080. this._supportsNormals = true;
  72081. this._supportsTangents = true;
  72082. this._vertexCount = 0;
  72083. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  72084. var target = _a[_i];
  72085. this._activeTargets.push(target);
  72086. this._tempInfluences[influenceCount++] = target.influence;
  72087. var positions = target.getPositions();
  72088. if (positions) {
  72089. this._supportsNormals = this._supportsNormals && target.hasNormals;
  72090. this._supportsTangents = this._supportsTangents && target.hasTangents;
  72091. var vertexCount = positions.length / 3;
  72092. if (this._vertexCount === 0) {
  72093. this._vertexCount = vertexCount;
  72094. }
  72095. else if (this._vertexCount !== vertexCount) {
  72096. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  72097. return;
  72098. }
  72099. }
  72100. }
  72101. if (!this._influences || this._influences.length !== influenceCount) {
  72102. this._influences = new Float32Array(influenceCount);
  72103. }
  72104. for (var index = 0; index < influenceCount; index++) {
  72105. this._influences[index] = this._tempInfluences[index];
  72106. }
  72107. if (needUpdate && this._scene) {
  72108. // Flag meshes as dirty to resync with the active targets
  72109. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  72110. var mesh = _c[_b];
  72111. if (mesh.morphTargetManager === this) {
  72112. mesh._syncGeometryWithMorphTargetManager();
  72113. }
  72114. }
  72115. }
  72116. };
  72117. // Statics
  72118. MorphTargetManager.Parse = function (serializationObject, scene) {
  72119. var result = new MorphTargetManager(scene);
  72120. result._uniqueId = serializationObject.id;
  72121. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  72122. var targetData = _a[_i];
  72123. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  72124. }
  72125. return result;
  72126. };
  72127. return MorphTargetManager;
  72128. }());
  72129. BABYLON.MorphTargetManager = MorphTargetManager;
  72130. })(BABYLON || (BABYLON = {}));
  72131. //# sourceMappingURL=babylon.morphTargetManager.js.map
  72132. var BABYLON;
  72133. (function (BABYLON) {
  72134. var Octree = /** @class */ (function () {
  72135. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  72136. if (maxDepth === void 0) { maxDepth = 2; }
  72137. this.maxDepth = maxDepth;
  72138. this.dynamicContent = new Array();
  72139. this._maxBlockCapacity = maxBlockCapacity || 64;
  72140. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  72141. this._creationFunc = creationFunc;
  72142. }
  72143. // Methods
  72144. Octree.prototype.update = function (worldMin, worldMax, entries) {
  72145. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  72146. };
  72147. Octree.prototype.addMesh = function (entry) {
  72148. for (var index = 0; index < this.blocks.length; index++) {
  72149. var block = this.blocks[index];
  72150. block.addEntry(entry);
  72151. }
  72152. };
  72153. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  72154. this._selectionContent.reset();
  72155. for (var index = 0; index < this.blocks.length; index++) {
  72156. var block = this.blocks[index];
  72157. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  72158. }
  72159. if (allowDuplicate) {
  72160. this._selectionContent.concat(this.dynamicContent);
  72161. }
  72162. else {
  72163. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  72164. }
  72165. return this._selectionContent;
  72166. };
  72167. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  72168. this._selectionContent.reset();
  72169. for (var index = 0; index < this.blocks.length; index++) {
  72170. var block = this.blocks[index];
  72171. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  72172. }
  72173. if (allowDuplicate) {
  72174. this._selectionContent.concat(this.dynamicContent);
  72175. }
  72176. else {
  72177. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  72178. }
  72179. return this._selectionContent;
  72180. };
  72181. Octree.prototype.intersectsRay = function (ray) {
  72182. this._selectionContent.reset();
  72183. for (var index = 0; index < this.blocks.length; index++) {
  72184. var block = this.blocks[index];
  72185. block.intersectsRay(ray, this._selectionContent);
  72186. }
  72187. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  72188. return this._selectionContent;
  72189. };
  72190. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  72191. target.blocks = new Array();
  72192. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  72193. // Segmenting space
  72194. for (var x = 0; x < 2; x++) {
  72195. for (var y = 0; y < 2; y++) {
  72196. for (var z = 0; z < 2; z++) {
  72197. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  72198. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  72199. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  72200. block.addEntries(entries);
  72201. target.blocks.push(block);
  72202. }
  72203. }
  72204. }
  72205. };
  72206. Octree.CreationFuncForMeshes = function (entry, block) {
  72207. var boundingInfo = entry.getBoundingInfo();
  72208. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  72209. block.entries.push(entry);
  72210. }
  72211. };
  72212. Octree.CreationFuncForSubMeshes = function (entry, block) {
  72213. var boundingInfo = entry.getBoundingInfo();
  72214. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  72215. block.entries.push(entry);
  72216. }
  72217. };
  72218. return Octree;
  72219. }());
  72220. BABYLON.Octree = Octree;
  72221. })(BABYLON || (BABYLON = {}));
  72222. //# sourceMappingURL=babylon.octree.js.map
  72223. var BABYLON;
  72224. (function (BABYLON) {
  72225. var OctreeBlock = /** @class */ (function () {
  72226. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  72227. this.entries = new Array();
  72228. this._boundingVectors = new Array();
  72229. this._capacity = capacity;
  72230. this._depth = depth;
  72231. this._maxDepth = maxDepth;
  72232. this._creationFunc = creationFunc;
  72233. this._minPoint = minPoint;
  72234. this._maxPoint = maxPoint;
  72235. this._boundingVectors.push(minPoint.clone());
  72236. this._boundingVectors.push(maxPoint.clone());
  72237. this._boundingVectors.push(minPoint.clone());
  72238. this._boundingVectors[2].x = maxPoint.x;
  72239. this._boundingVectors.push(minPoint.clone());
  72240. this._boundingVectors[3].y = maxPoint.y;
  72241. this._boundingVectors.push(minPoint.clone());
  72242. this._boundingVectors[4].z = maxPoint.z;
  72243. this._boundingVectors.push(maxPoint.clone());
  72244. this._boundingVectors[5].z = minPoint.z;
  72245. this._boundingVectors.push(maxPoint.clone());
  72246. this._boundingVectors[6].x = minPoint.x;
  72247. this._boundingVectors.push(maxPoint.clone());
  72248. this._boundingVectors[7].y = minPoint.y;
  72249. }
  72250. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  72251. // Property
  72252. get: function () {
  72253. return this._capacity;
  72254. },
  72255. enumerable: true,
  72256. configurable: true
  72257. });
  72258. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  72259. get: function () {
  72260. return this._minPoint;
  72261. },
  72262. enumerable: true,
  72263. configurable: true
  72264. });
  72265. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  72266. get: function () {
  72267. return this._maxPoint;
  72268. },
  72269. enumerable: true,
  72270. configurable: true
  72271. });
  72272. // Methods
  72273. OctreeBlock.prototype.addEntry = function (entry) {
  72274. if (this.blocks) {
  72275. for (var index = 0; index < this.blocks.length; index++) {
  72276. var block = this.blocks[index];
  72277. block.addEntry(entry);
  72278. }
  72279. return;
  72280. }
  72281. this._creationFunc(entry, this);
  72282. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  72283. this.createInnerBlocks();
  72284. }
  72285. };
  72286. OctreeBlock.prototype.addEntries = function (entries) {
  72287. for (var index = 0; index < entries.length; index++) {
  72288. var mesh = entries[index];
  72289. this.addEntry(mesh);
  72290. }
  72291. };
  72292. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  72293. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  72294. if (this.blocks) {
  72295. for (var index = 0; index < this.blocks.length; index++) {
  72296. var block = this.blocks[index];
  72297. block.select(frustumPlanes, selection, allowDuplicate);
  72298. }
  72299. return;
  72300. }
  72301. if (allowDuplicate) {
  72302. selection.concat(this.entries);
  72303. }
  72304. else {
  72305. selection.concatWithNoDuplicate(this.entries);
  72306. }
  72307. }
  72308. };
  72309. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  72310. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  72311. if (this.blocks) {
  72312. for (var index = 0; index < this.blocks.length; index++) {
  72313. var block = this.blocks[index];
  72314. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  72315. }
  72316. return;
  72317. }
  72318. if (allowDuplicate) {
  72319. selection.concat(this.entries);
  72320. }
  72321. else {
  72322. selection.concatWithNoDuplicate(this.entries);
  72323. }
  72324. }
  72325. };
  72326. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  72327. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  72328. if (this.blocks) {
  72329. for (var index = 0; index < this.blocks.length; index++) {
  72330. var block = this.blocks[index];
  72331. block.intersectsRay(ray, selection);
  72332. }
  72333. return;
  72334. }
  72335. selection.concatWithNoDuplicate(this.entries);
  72336. }
  72337. };
  72338. OctreeBlock.prototype.createInnerBlocks = function () {
  72339. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  72340. };
  72341. return OctreeBlock;
  72342. }());
  72343. BABYLON.OctreeBlock = OctreeBlock;
  72344. })(BABYLON || (BABYLON = {}));
  72345. //# sourceMappingURL=babylon.octreeBlock.js.map
  72346. var BABYLON;
  72347. (function (BABYLON) {
  72348. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  72349. __extends(VRDistortionCorrectionPostProcess, _super);
  72350. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  72351. var _this = _super.call(this, name, "vrDistortionCorrection", [
  72352. 'LensCenter',
  72353. 'Scale',
  72354. 'ScaleIn',
  72355. 'HmdWarpParam'
  72356. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  72357. _this._isRightEye = isRightEye;
  72358. _this._distortionFactors = vrMetrics.distortionK;
  72359. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  72360. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  72361. _this.adaptScaleToCurrentViewport = true;
  72362. _this.onSizeChangedObservable.add(function () {
  72363. _this.aspectRatio = _this.width * .5 / _this.height;
  72364. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  72365. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  72366. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  72367. });
  72368. _this.onApplyObservable.add(function (effect) {
  72369. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  72370. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  72371. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  72372. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  72373. });
  72374. return _this;
  72375. }
  72376. return VRDistortionCorrectionPostProcess;
  72377. }(BABYLON.PostProcess));
  72378. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  72379. })(BABYLON || (BABYLON = {}));
  72380. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  72381. var BABYLON;
  72382. (function (BABYLON) {
  72383. var AnaglyphPostProcess = /** @class */ (function (_super) {
  72384. __extends(AnaglyphPostProcess, _super);
  72385. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  72386. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  72387. _this._passedProcess = rigCameras[0]._rigPostProcess;
  72388. _this.onApplyObservable.add(function (effect) {
  72389. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  72390. });
  72391. return _this;
  72392. }
  72393. return AnaglyphPostProcess;
  72394. }(BABYLON.PostProcess));
  72395. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  72396. })(BABYLON || (BABYLON = {}));
  72397. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  72398. var BABYLON;
  72399. (function (BABYLON) {
  72400. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  72401. __extends(StereoscopicInterlacePostProcess, _super);
  72402. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  72403. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  72404. _this._passedProcess = rigCameras[0]._rigPostProcess;
  72405. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  72406. _this.onSizeChangedObservable.add(function () {
  72407. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  72408. });
  72409. _this.onApplyObservable.add(function (effect) {
  72410. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  72411. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  72412. });
  72413. return _this;
  72414. }
  72415. return StereoscopicInterlacePostProcess;
  72416. }(BABYLON.PostProcess));
  72417. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  72418. })(BABYLON || (BABYLON = {}));
  72419. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  72420. var BABYLON;
  72421. (function (BABYLON) {
  72422. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  72423. function FreeCameraDeviceOrientationInput() {
  72424. var _this = this;
  72425. this._screenOrientationAngle = 0;
  72426. this._screenQuaternion = new BABYLON.Quaternion();
  72427. this._alpha = 0;
  72428. this._beta = 0;
  72429. this._gamma = 0;
  72430. this._orientationChanged = function () {
  72431. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  72432. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  72433. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  72434. };
  72435. this._deviceOrientation = function (evt) {
  72436. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  72437. _this._beta = evt.beta !== null ? evt.beta : 0;
  72438. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  72439. };
  72440. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  72441. this._orientationChanged();
  72442. }
  72443. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  72444. get: function () {
  72445. return this._camera;
  72446. },
  72447. set: function (camera) {
  72448. this._camera = camera;
  72449. if (this._camera != null && !this._camera.rotationQuaternion) {
  72450. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  72451. }
  72452. },
  72453. enumerable: true,
  72454. configurable: true
  72455. });
  72456. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  72457. window.addEventListener("orientationchange", this._orientationChanged);
  72458. window.addEventListener("deviceorientation", this._deviceOrientation);
  72459. //In certain cases, the attach control is called AFTER orientation was changed,
  72460. //So this is needed.
  72461. this._orientationChanged();
  72462. };
  72463. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  72464. window.removeEventListener("orientationchange", this._orientationChanged);
  72465. window.removeEventListener("deviceorientation", this._deviceOrientation);
  72466. };
  72467. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  72468. //if no device orientation provided, don't update the rotation.
  72469. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  72470. if (!this._alpha)
  72471. return;
  72472. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  72473. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  72474. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  72475. //Mirror on XY Plane
  72476. this._camera.rotationQuaternion.z *= -1;
  72477. this._camera.rotationQuaternion.w *= -1;
  72478. };
  72479. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  72480. return "FreeCameraDeviceOrientationInput";
  72481. };
  72482. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  72483. return "deviceOrientation";
  72484. };
  72485. return FreeCameraDeviceOrientationInput;
  72486. }());
  72487. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  72488. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  72489. })(BABYLON || (BABYLON = {}));
  72490. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  72491. var BABYLON;
  72492. (function (BABYLON) {
  72493. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  72494. function ArcRotateCameraVRDeviceOrientationInput() {
  72495. this.alphaCorrection = 1;
  72496. this.betaCorrection = 1;
  72497. this.gammaCorrection = 1;
  72498. this._alpha = 0;
  72499. this._gamma = 0;
  72500. this._dirty = false;
  72501. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  72502. }
  72503. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  72504. this.camera.attachControl(element, noPreventDefault);
  72505. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  72506. };
  72507. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  72508. if (evt.alpha !== null) {
  72509. this._alpha = +evt.alpha | 0;
  72510. }
  72511. if (evt.gamma !== null) {
  72512. this._gamma = +evt.gamma | 0;
  72513. }
  72514. this._dirty = true;
  72515. };
  72516. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  72517. if (this._dirty) {
  72518. this._dirty = false;
  72519. if (this._gamma < 0) {
  72520. this._gamma = 180 + this._gamma;
  72521. }
  72522. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  72523. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  72524. }
  72525. };
  72526. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  72527. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  72528. };
  72529. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  72530. return "ArcRotateCameraVRDeviceOrientationInput";
  72531. };
  72532. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  72533. return "VRDeviceOrientation";
  72534. };
  72535. return ArcRotateCameraVRDeviceOrientationInput;
  72536. }());
  72537. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  72538. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  72539. })(BABYLON || (BABYLON = {}));
  72540. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  72541. var BABYLON;
  72542. (function (BABYLON) {
  72543. var VRCameraMetrics = /** @class */ (function () {
  72544. function VRCameraMetrics() {
  72545. this.compensateDistortion = true;
  72546. }
  72547. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  72548. get: function () {
  72549. return this.hResolution / (2 * this.vResolution);
  72550. },
  72551. enumerable: true,
  72552. configurable: true
  72553. });
  72554. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  72555. get: function () {
  72556. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  72557. },
  72558. enumerable: true,
  72559. configurable: true
  72560. });
  72561. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  72562. get: function () {
  72563. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  72564. var h = (4 * meters) / this.hScreenSize;
  72565. return BABYLON.Matrix.Translation(h, 0, 0);
  72566. },
  72567. enumerable: true,
  72568. configurable: true
  72569. });
  72570. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  72571. get: function () {
  72572. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  72573. var h = (4 * meters) / this.hScreenSize;
  72574. return BABYLON.Matrix.Translation(-h, 0, 0);
  72575. },
  72576. enumerable: true,
  72577. configurable: true
  72578. });
  72579. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  72580. get: function () {
  72581. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  72582. },
  72583. enumerable: true,
  72584. configurable: true
  72585. });
  72586. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  72587. get: function () {
  72588. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  72589. },
  72590. enumerable: true,
  72591. configurable: true
  72592. });
  72593. VRCameraMetrics.GetDefault = function () {
  72594. var result = new VRCameraMetrics();
  72595. result.hResolution = 1280;
  72596. result.vResolution = 800;
  72597. result.hScreenSize = 0.149759993;
  72598. result.vScreenSize = 0.0935999975;
  72599. result.vScreenCenter = 0.0467999987;
  72600. result.eyeToScreenDistance = 0.0410000011;
  72601. result.lensSeparationDistance = 0.0635000020;
  72602. result.interpupillaryDistance = 0.0640000030;
  72603. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  72604. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  72605. result.postProcessScaleFactor = 1.714605507808412;
  72606. result.lensCenterOffset = 0.151976421;
  72607. return result;
  72608. };
  72609. return VRCameraMetrics;
  72610. }());
  72611. BABYLON.VRCameraMetrics = VRCameraMetrics;
  72612. })(BABYLON || (BABYLON = {}));
  72613. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  72614. var BABYLON;
  72615. (function (BABYLON) {
  72616. var WebVRFreeCamera = /** @class */ (function (_super) {
  72617. __extends(WebVRFreeCamera, _super);
  72618. function WebVRFreeCamera(name, position, scene, webVROptions) {
  72619. if (webVROptions === void 0) { webVROptions = {}; }
  72620. var _this = _super.call(this, name, position, scene) || this;
  72621. _this.webVROptions = webVROptions;
  72622. _this._vrDevice = null;
  72623. _this.rawPose = null;
  72624. _this._specsVersion = "1.1";
  72625. _this._attached = false;
  72626. _this._descendants = [];
  72627. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  72628. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  72629. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  72630. _this._standingMatrix = null;
  72631. // Represents device position and rotation in babylon space
  72632. _this.devicePosition = BABYLON.Vector3.Zero();
  72633. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  72634. _this.deviceScaleFactor = 1;
  72635. _this._deviceToWorld = BABYLON.Matrix.Identity();
  72636. _this._worldToDevice = BABYLON.Matrix.Identity();
  72637. _this.controllers = [];
  72638. _this.onControllersAttachedObservable = new BABYLON.Observable();
  72639. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  72640. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  72641. _this._defaultHeight = 0;
  72642. _this.deviceDistanceToRoomGround = function () {
  72643. if (_this._standingMatrix) {
  72644. // Add standing matrix offset to get real offset from ground in room
  72645. _this._standingMatrix.getTranslationToRef(_this._workingVector);
  72646. return _this._deviceRoomPosition.y + _this._workingVector.y;
  72647. }
  72648. else {
  72649. return _this._defaultHeight;
  72650. }
  72651. };
  72652. _this.useStandingMatrix = function (callback) {
  72653. if (callback === void 0) { callback = function (bool) { }; }
  72654. // Use standing matrix if availible
  72655. if (!navigator || !navigator.getVRDisplays) {
  72656. callback(false);
  72657. }
  72658. else {
  72659. navigator.getVRDisplays().then(function (displays) {
  72660. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  72661. callback(false);
  72662. }
  72663. else {
  72664. _this._standingMatrix = new BABYLON.Matrix();
  72665. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  72666. if (!_this.getScene().useRightHandedSystem) {
  72667. [2, 6, 8, 9, 14].forEach(function (num) {
  72668. if (_this._standingMatrix) {
  72669. _this._standingMatrix.m[num] *= -1;
  72670. }
  72671. });
  72672. }
  72673. callback(true);
  72674. }
  72675. });
  72676. }
  72677. };
  72678. _this._workingVector = BABYLON.Vector3.Zero();
  72679. _this._oneVector = BABYLON.Vector3.One();
  72680. _this._workingMatrix = BABYLON.Matrix.Identity();
  72681. _this._cache.position = BABYLON.Vector3.Zero();
  72682. if (webVROptions.defaultHeight) {
  72683. _this._defaultHeight = webVROptions.defaultHeight;
  72684. _this.position.y = _this._defaultHeight;
  72685. }
  72686. _this.minZ = 0.1;
  72687. //legacy support - the compensation boolean was removed.
  72688. if (arguments.length === 5) {
  72689. _this.webVROptions = arguments[4];
  72690. }
  72691. // default webVR options
  72692. if (_this.webVROptions.trackPosition == undefined) {
  72693. _this.webVROptions.trackPosition = true;
  72694. }
  72695. if (_this.webVROptions.controllerMeshes == undefined) {
  72696. _this.webVROptions.controllerMeshes = true;
  72697. }
  72698. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  72699. _this.webVROptions.defaultLightingOnControllers = true;
  72700. }
  72701. _this.rotationQuaternion = new BABYLON.Quaternion();
  72702. if (_this.webVROptions && _this.webVROptions.positionScale) {
  72703. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  72704. }
  72705. //enable VR
  72706. var engine = _this.getEngine();
  72707. _this._onVREnabled = function (success) { if (success) {
  72708. _this.initControllers();
  72709. } };
  72710. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  72711. engine.initWebVR().add(function (event) {
  72712. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  72713. return;
  72714. }
  72715. _this._vrDevice = event.vrDisplay;
  72716. //reset the rig parameters.
  72717. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  72718. if (_this._attached) {
  72719. _this.getEngine().enableVR();
  72720. }
  72721. });
  72722. if (typeof (VRFrameData) !== "undefined")
  72723. _this._frameData = new VRFrameData();
  72724. /**
  72725. * The idea behind the following lines:
  72726. * objects that have the camera as parent should actually have the rig cameras as a parent.
  72727. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  72728. * the second will not show it correctly.
  72729. *
  72730. * To solve this - each object that has the camera as parent will be added to a protected array.
  72731. * When the rig camera renders, it will take this array and set all of those to be its children.
  72732. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  72733. * Amazing!
  72734. */
  72735. scene.onBeforeCameraRenderObservable.add(function (camera) {
  72736. if (camera.parent === _this && _this.rigParenting) {
  72737. _this._descendants = _this.getDescendants(true, function (n) {
  72738. // don't take the cameras or the controllers!
  72739. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  72740. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  72741. return !isController && !isRigCamera;
  72742. });
  72743. _this._descendants.forEach(function (node) {
  72744. node.parent = camera;
  72745. });
  72746. }
  72747. });
  72748. scene.onAfterCameraRenderObservable.add(function (camera) {
  72749. if (camera.parent === _this && _this.rigParenting) {
  72750. _this._descendants.forEach(function (node) {
  72751. node.parent = _this;
  72752. });
  72753. }
  72754. });
  72755. return _this;
  72756. }
  72757. WebVRFreeCamera.prototype.dispose = function () {
  72758. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  72759. _super.prototype.dispose.call(this);
  72760. };
  72761. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  72762. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  72763. var gp = _a[_i];
  72764. if (gp.hand === name) {
  72765. return gp;
  72766. }
  72767. }
  72768. return null;
  72769. };
  72770. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  72771. get: function () {
  72772. if (!this._leftController) {
  72773. this._leftController = this.getControllerByName("left");
  72774. }
  72775. return this._leftController;
  72776. },
  72777. enumerable: true,
  72778. configurable: true
  72779. });
  72780. ;
  72781. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  72782. get: function () {
  72783. if (!this._rightController) {
  72784. this._rightController = this.getControllerByName("right");
  72785. }
  72786. return this._rightController;
  72787. },
  72788. enumerable: true,
  72789. configurable: true
  72790. });
  72791. ;
  72792. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  72793. if (length === void 0) { length = 100; }
  72794. if (this.leftCamera) {
  72795. // Use left eye to avoid computation to compute center on every call
  72796. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  72797. }
  72798. else {
  72799. return _super.prototype.getForwardRay.call(this, length);
  72800. }
  72801. };
  72802. WebVRFreeCamera.prototype._checkInputs = function () {
  72803. if (this._vrDevice && this._vrDevice.isPresenting) {
  72804. this._vrDevice.getFrameData(this._frameData);
  72805. this.updateFromDevice(this._frameData.pose);
  72806. }
  72807. _super.prototype._checkInputs.call(this);
  72808. };
  72809. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  72810. if (poseData && poseData.orientation) {
  72811. this.rawPose = poseData;
  72812. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  72813. if (this.getScene().useRightHandedSystem) {
  72814. this._deviceRoomRotationQuaternion.z *= -1;
  72815. this._deviceRoomRotationQuaternion.w *= -1;
  72816. }
  72817. if (this.webVROptions.trackPosition && this.rawPose.position) {
  72818. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  72819. if (this.getScene().useRightHandedSystem) {
  72820. this._deviceRoomPosition.z *= -1;
  72821. }
  72822. }
  72823. }
  72824. };
  72825. /**
  72826. * WebVR's attach control will start broadcasting frames to the device.
  72827. * Note that in certain browsers (chrome for example) this function must be called
  72828. * within a user-interaction callback. Example:
  72829. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  72830. *
  72831. * @param {HTMLElement} element
  72832. * @param {boolean} [noPreventDefault]
  72833. *
  72834. * @memberOf WebVRFreeCamera
  72835. */
  72836. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  72837. _super.prototype.attachControl.call(this, element, noPreventDefault);
  72838. this._attached = true;
  72839. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  72840. if (this._vrDevice) {
  72841. this.getEngine().enableVR();
  72842. }
  72843. };
  72844. WebVRFreeCamera.prototype.detachControl = function (element) {
  72845. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72846. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72847. _super.prototype.detachControl.call(this, element);
  72848. this._attached = false;
  72849. this.getEngine().disableVR();
  72850. };
  72851. WebVRFreeCamera.prototype.getClassName = function () {
  72852. return "WebVRFreeCamera";
  72853. };
  72854. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  72855. //uses the vrDisplay's "resetPose()".
  72856. //pitch and roll won't be affected.
  72857. this._vrDevice.resetPose();
  72858. };
  72859. WebVRFreeCamera.prototype._updateRigCameras = function () {
  72860. var camLeft = this._rigCameras[0];
  72861. var camRight = this._rigCameras[1];
  72862. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72863. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72864. camLeft.position.copyFrom(this._deviceRoomPosition);
  72865. camRight.position.copyFrom(this._deviceRoomPosition);
  72866. };
  72867. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  72868. var _this = this;
  72869. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  72870. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  72871. if (!this.updateCacheCalled) {
  72872. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  72873. this.updateCacheCalled = true;
  72874. this.update();
  72875. }
  72876. // Set working vector to the device position in room space rotated by the new rotation
  72877. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  72878. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  72879. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  72880. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  72881. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  72882. // Add translation from anchor position
  72883. this._deviceToWorld.getTranslationToRef(this._workingVector);
  72884. this._workingVector.addInPlace(this.position);
  72885. this._workingVector.subtractInPlace(this._cache.position);
  72886. this._deviceToWorld.setTranslation(this._workingVector);
  72887. // Set an inverted matrix to be used when updating the camera
  72888. this._deviceToWorld.invertToRef(this._worldToDevice);
  72889. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  72890. this.controllers.forEach(function (controller) {
  72891. controller._deviceToWorld = _this._deviceToWorld;
  72892. controller.update();
  72893. });
  72894. }
  72895. if (!ignoreParentClass) {
  72896. _super.prototype._updateCache.call(this);
  72897. }
  72898. this.updateCacheCalled = false;
  72899. };
  72900. WebVRFreeCamera.prototype.update = function () {
  72901. // Get current device position in babylon world
  72902. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  72903. // Get current device rotation in babylon world
  72904. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  72905. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  72906. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72907. _super.prototype.update.call(this);
  72908. };
  72909. WebVRFreeCamera.prototype._getViewMatrix = function () {
  72910. return BABYLON.Matrix.Identity();
  72911. };
  72912. /**
  72913. * This function is called by the two RIG cameras.
  72914. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  72915. */
  72916. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  72917. var _this = this;
  72918. //WebVR 1.1
  72919. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  72920. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  72921. if (!this.getScene().useRightHandedSystem) {
  72922. [2, 6, 8, 9, 14].forEach(function (num) {
  72923. _this._webvrViewMatrix.m[num] *= -1;
  72924. });
  72925. }
  72926. // update the camera rotation matrix
  72927. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  72928. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  72929. // Computing target and final matrix
  72930. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  72931. var parentCamera = this._cameraRigParams["parentCamera"];
  72932. // should the view matrix be updated with scale and position offset?
  72933. if (parentCamera.deviceScaleFactor !== 1) {
  72934. this._webvrViewMatrix.invert();
  72935. // scale the position, if set
  72936. if (parentCamera.deviceScaleFactor) {
  72937. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  72938. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  72939. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  72940. }
  72941. this._webvrViewMatrix.invert();
  72942. }
  72943. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  72944. return this._webvrViewMatrix;
  72945. };
  72946. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  72947. var _this = this;
  72948. var parentCamera = this.parent;
  72949. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  72950. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  72951. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  72952. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  72953. //babylon compatible matrix
  72954. if (!this.getScene().useRightHandedSystem) {
  72955. [8, 9, 10, 11].forEach(function (num) {
  72956. _this._projectionMatrix.m[num] *= -1;
  72957. });
  72958. }
  72959. return this._projectionMatrix;
  72960. };
  72961. WebVRFreeCamera.prototype.initControllers = function () {
  72962. var _this = this;
  72963. this.controllers = [];
  72964. var manager = this.getScene().gamepadManager;
  72965. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72966. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  72967. var webVrController = gamepad;
  72968. if (webVrController.defaultModel) {
  72969. webVrController.defaultModel.setEnabled(false);
  72970. }
  72971. if (webVrController.hand === "right") {
  72972. _this._rightController = null;
  72973. }
  72974. if (webVrController.hand === "left") {
  72975. _this._rightController = null;
  72976. }
  72977. var controllerIndex = _this.controllers.indexOf(webVrController);
  72978. if (controllerIndex !== -1) {
  72979. _this.controllers.splice(controllerIndex, 1);
  72980. }
  72981. }
  72982. });
  72983. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72984. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  72985. var webVrController_1 = gamepad;
  72986. webVrController_1._deviceToWorld = _this._deviceToWorld;
  72987. if (_this.webVROptions.controllerMeshes) {
  72988. if (webVrController_1.defaultModel) {
  72989. webVrController_1.defaultModel.setEnabled(true);
  72990. }
  72991. else {
  72992. // Load the meshes
  72993. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  72994. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  72995. if (_this.webVROptions.defaultLightingOnControllers) {
  72996. if (!_this._lightOnControllers) {
  72997. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  72998. }
  72999. var activateLightOnSubMeshes_1 = function (mesh, light) {
  73000. var children = mesh.getChildren();
  73001. if (children.length !== 0) {
  73002. children.forEach(function (mesh) {
  73003. light.includedOnlyMeshes.push(mesh);
  73004. activateLightOnSubMeshes_1(mesh, light);
  73005. });
  73006. }
  73007. };
  73008. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  73009. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  73010. }
  73011. });
  73012. }
  73013. }
  73014. webVrController_1.attachToPoseControlledCamera(_this);
  73015. // since this is async - sanity check. Is the controller already stored?
  73016. if (_this.controllers.indexOf(webVrController_1) === -1) {
  73017. //add to the controllers array
  73018. _this.controllers.push(webVrController_1);
  73019. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  73020. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  73021. // So we're overriding setting left & right manually to be sure
  73022. var firstViveWandDetected = false;
  73023. for (var i = 0; i < _this.controllers.length; i++) {
  73024. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  73025. if (!firstViveWandDetected) {
  73026. firstViveWandDetected = true;
  73027. _this.controllers[i].hand = "left";
  73028. }
  73029. else {
  73030. _this.controllers[i].hand = "right";
  73031. }
  73032. }
  73033. }
  73034. //did we find enough controllers? Great! let the developer know.
  73035. if (_this.controllers.length >= 2) {
  73036. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  73037. }
  73038. }
  73039. }
  73040. });
  73041. };
  73042. return WebVRFreeCamera;
  73043. }(BABYLON.FreeCamera));
  73044. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  73045. })(BABYLON || (BABYLON = {}));
  73046. //# sourceMappingURL=babylon.webVRCamera.js.map
  73047. var BABYLON;
  73048. (function (BABYLON) {
  73049. // We're mainly based on the logic defined into the FreeCamera code
  73050. var DeviceOrientationCamera = /** @class */ (function (_super) {
  73051. __extends(DeviceOrientationCamera, _super);
  73052. function DeviceOrientationCamera(name, position, scene) {
  73053. var _this = _super.call(this, name, position, scene) || this;
  73054. _this._quaternionCache = new BABYLON.Quaternion();
  73055. _this.inputs.addDeviceOrientation();
  73056. return _this;
  73057. }
  73058. DeviceOrientationCamera.prototype.getClassName = function () {
  73059. return "DeviceOrientationCamera";
  73060. };
  73061. DeviceOrientationCamera.prototype._checkInputs = function () {
  73062. _super.prototype._checkInputs.call(this);
  73063. this._quaternionCache.copyFrom(this.rotationQuaternion);
  73064. if (this._initialQuaternion) {
  73065. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  73066. }
  73067. };
  73068. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  73069. var _this = this;
  73070. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  73071. //can only work if this camera has a rotation quaternion already.
  73072. if (!this.rotationQuaternion)
  73073. return;
  73074. if (!this._initialQuaternion) {
  73075. this._initialQuaternion = new BABYLON.Quaternion();
  73076. }
  73077. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  73078. ['x', 'y', 'z'].forEach(function (axisName) {
  73079. if (!axis[axisName]) {
  73080. _this._initialQuaternion[axisName] = 0;
  73081. }
  73082. else {
  73083. _this._initialQuaternion[axisName] *= -1;
  73084. }
  73085. });
  73086. this._initialQuaternion.normalize();
  73087. //force rotation update
  73088. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  73089. };
  73090. return DeviceOrientationCamera;
  73091. }(BABYLON.FreeCamera));
  73092. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  73093. })(BABYLON || (BABYLON = {}));
  73094. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  73095. var BABYLON;
  73096. (function (BABYLON) {
  73097. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  73098. __extends(VRDeviceOrientationFreeCamera, _super);
  73099. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  73100. if (compensateDistortion === void 0) { compensateDistortion = true; }
  73101. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  73102. var _this = _super.call(this, name, position, scene) || this;
  73103. vrCameraMetrics.compensateDistortion = compensateDistortion;
  73104. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  73105. return _this;
  73106. }
  73107. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  73108. return "VRDeviceOrientationFreeCamera";
  73109. };
  73110. return VRDeviceOrientationFreeCamera;
  73111. }(BABYLON.DeviceOrientationCamera));
  73112. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  73113. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  73114. __extends(VRDeviceOrientationGamepadCamera, _super);
  73115. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  73116. if (compensateDistortion === void 0) { compensateDistortion = true; }
  73117. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  73118. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  73119. _this.inputs.addGamepad();
  73120. return _this;
  73121. }
  73122. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  73123. return "VRDeviceOrientationGamepadCamera";
  73124. };
  73125. return VRDeviceOrientationGamepadCamera;
  73126. }(VRDeviceOrientationFreeCamera));
  73127. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  73128. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  73129. __extends(VRDeviceOrientationArcRotateCamera, _super);
  73130. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  73131. if (compensateDistortion === void 0) { compensateDistortion = true; }
  73132. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  73133. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  73134. vrCameraMetrics.compensateDistortion = compensateDistortion;
  73135. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  73136. _this.inputs.addVRDeviceOrientation();
  73137. return _this;
  73138. }
  73139. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  73140. return "VRDeviceOrientationArcRotateCamera";
  73141. };
  73142. return VRDeviceOrientationArcRotateCamera;
  73143. }(BABYLON.ArcRotateCamera));
  73144. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  73145. })(BABYLON || (BABYLON = {}));
  73146. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  73147. var BABYLON;
  73148. (function (BABYLON) {
  73149. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  73150. __extends(AnaglyphFreeCamera, _super);
  73151. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  73152. var _this = _super.call(this, name, position, scene) || this;
  73153. _this.interaxialDistance = interaxialDistance;
  73154. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73155. return _this;
  73156. }
  73157. AnaglyphFreeCamera.prototype.getClassName = function () {
  73158. return "AnaglyphFreeCamera";
  73159. };
  73160. return AnaglyphFreeCamera;
  73161. }(BABYLON.FreeCamera));
  73162. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  73163. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  73164. __extends(AnaglyphArcRotateCamera, _super);
  73165. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  73166. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  73167. _this.interaxialDistance = interaxialDistance;
  73168. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73169. return _this;
  73170. }
  73171. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  73172. return "AnaglyphArcRotateCamera";
  73173. };
  73174. return AnaglyphArcRotateCamera;
  73175. }(BABYLON.ArcRotateCamera));
  73176. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  73177. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  73178. __extends(AnaglyphGamepadCamera, _super);
  73179. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  73180. var _this = _super.call(this, name, position, scene) || this;
  73181. _this.interaxialDistance = interaxialDistance;
  73182. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73183. return _this;
  73184. }
  73185. AnaglyphGamepadCamera.prototype.getClassName = function () {
  73186. return "AnaglyphGamepadCamera";
  73187. };
  73188. return AnaglyphGamepadCamera;
  73189. }(BABYLON.GamepadCamera));
  73190. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  73191. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  73192. __extends(AnaglyphUniversalCamera, _super);
  73193. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  73194. var _this = _super.call(this, name, position, scene) || this;
  73195. _this.interaxialDistance = interaxialDistance;
  73196. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73197. return _this;
  73198. }
  73199. AnaglyphUniversalCamera.prototype.getClassName = function () {
  73200. return "AnaglyphUniversalCamera";
  73201. };
  73202. return AnaglyphUniversalCamera;
  73203. }(BABYLON.UniversalCamera));
  73204. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  73205. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  73206. __extends(StereoscopicFreeCamera, _super);
  73207. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73208. var _this = _super.call(this, name, position, scene) || this;
  73209. _this.interaxialDistance = interaxialDistance;
  73210. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73211. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73212. return _this;
  73213. }
  73214. StereoscopicFreeCamera.prototype.getClassName = function () {
  73215. return "StereoscopicFreeCamera";
  73216. };
  73217. return StereoscopicFreeCamera;
  73218. }(BABYLON.FreeCamera));
  73219. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  73220. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  73221. __extends(StereoscopicArcRotateCamera, _super);
  73222. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  73223. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  73224. _this.interaxialDistance = interaxialDistance;
  73225. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73226. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73227. return _this;
  73228. }
  73229. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  73230. return "StereoscopicArcRotateCamera";
  73231. };
  73232. return StereoscopicArcRotateCamera;
  73233. }(BABYLON.ArcRotateCamera));
  73234. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  73235. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  73236. __extends(StereoscopicGamepadCamera, _super);
  73237. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73238. var _this = _super.call(this, name, position, scene) || this;
  73239. _this.interaxialDistance = interaxialDistance;
  73240. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73241. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73242. return _this;
  73243. }
  73244. StereoscopicGamepadCamera.prototype.getClassName = function () {
  73245. return "StereoscopicGamepadCamera";
  73246. };
  73247. return StereoscopicGamepadCamera;
  73248. }(BABYLON.GamepadCamera));
  73249. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  73250. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  73251. __extends(StereoscopicUniversalCamera, _super);
  73252. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73253. var _this = _super.call(this, name, position, scene) || this;
  73254. _this.interaxialDistance = interaxialDistance;
  73255. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73256. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73257. return _this;
  73258. }
  73259. StereoscopicUniversalCamera.prototype.getClassName = function () {
  73260. return "StereoscopicUniversalCamera";
  73261. };
  73262. return StereoscopicUniversalCamera;
  73263. }(BABYLON.UniversalCamera));
  73264. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  73265. })(BABYLON || (BABYLON = {}));
  73266. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  73267. var BABYLON;
  73268. (function (BABYLON) {
  73269. var VRExperienceHelper = /** @class */ (function () {
  73270. function VRExperienceHelper(scene, webVROptions) {
  73271. if (webVROptions === void 0) { webVROptions = {}; }
  73272. var _this = this;
  73273. this.webVROptions = webVROptions;
  73274. // Can the system support WebVR, even if a headset isn't plugged in?
  73275. this._webVRsupported = false;
  73276. // If WebVR is supported, is a headset plugged in and are we ready to present?
  73277. this._webVRready = false;
  73278. // Are we waiting for the requestPresent callback to complete?
  73279. this._webVRrequesting = false;
  73280. // Are we presenting to the headset right now?
  73281. this._webVRpresenting = false;
  73282. // Are we presenting in the fullscreen fallback?
  73283. this._fullscreenVRpresenting = false;
  73284. /**
  73285. * Observable raised when entering VR.
  73286. */
  73287. this.onEnteringVRObservable = new BABYLON.Observable();
  73288. /**
  73289. * Observable raised when exiting VR.
  73290. */
  73291. this.onExitingVRObservable = new BABYLON.Observable();
  73292. /**
  73293. * Observable raised when controller mesh is loaded.
  73294. */
  73295. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  73296. this._useCustomVRButton = false;
  73297. this._teleportationRequested = false;
  73298. this._teleportationEnabledOnLeftController = false;
  73299. this._teleportationEnabledOnRightController = false;
  73300. this._interactionsEnabledOnLeftController = false;
  73301. this._interactionsEnabledOnRightController = false;
  73302. this._leftControllerReady = false;
  73303. this._rightControllerReady = false;
  73304. this._floorMeshesCollection = [];
  73305. this._teleportationAllowed = false;
  73306. this._rotationAllowed = true;
  73307. this._teleportationRequestInitiated = false;
  73308. this._teleportationBackRequestInitiated = false;
  73309. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  73310. this._rotationRightAsked = false;
  73311. this._rotationLeftAsked = false;
  73312. this._isDefaultTeleportationTarget = true;
  73313. this._teleportationFillColor = "#444444";
  73314. this._teleportationBorderColor = "#FFFFFF";
  73315. this._rotationAngle = 0;
  73316. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  73317. this._padSensibilityUp = 0.65;
  73318. this._padSensibilityDown = 0.35;
  73319. /**
  73320. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  73321. */
  73322. this.onNewMeshSelected = new BABYLON.Observable();
  73323. /**
  73324. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  73325. */
  73326. this.onNewMeshPicked = new BABYLON.Observable();
  73327. /**
  73328. * Observable raised before camera teleportation
  73329. */
  73330. this.onBeforeCameraTeleport = new BABYLON.Observable();
  73331. /**
  73332. * Observable raised after camera teleportation
  73333. */
  73334. this.onAfterCameraTeleport = new BABYLON.Observable();
  73335. /**
  73336. * Observable raised when current selected mesh gets unselected
  73337. */
  73338. this.onSelectedMeshUnselected = new BABYLON.Observable();
  73339. /**
  73340. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  73341. */
  73342. this.teleportationEnabled = true;
  73343. this._pointerDownOnMeshAsked = false;
  73344. this._isActionableMesh = false;
  73345. this._teleportationInitialized = false;
  73346. this._interactionsEnabled = false;
  73347. this._interactionsRequested = false;
  73348. this._displayGaze = true;
  73349. this._displayLaserPointer = true;
  73350. this._dpadPressed = true;
  73351. this._onResize = function () {
  73352. _this.moveButtonToBottomRight();
  73353. if (_this._fullscreenVRpresenting && _this._webVRready) {
  73354. _this.exitVR();
  73355. }
  73356. };
  73357. this._onFullscreenChange = function () {
  73358. if (document.fullscreen !== undefined) {
  73359. _this._fullscreenVRpresenting = document.fullscreen;
  73360. }
  73361. else if (document.mozFullScreen !== undefined) {
  73362. _this._fullscreenVRpresenting = document.mozFullScreen;
  73363. }
  73364. else if (document.webkitIsFullScreen !== undefined) {
  73365. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  73366. }
  73367. else if (document.msIsFullScreen !== undefined) {
  73368. _this._fullscreenVRpresenting = document.msIsFullScreen;
  73369. }
  73370. if (!_this._fullscreenVRpresenting && _this._canvas) {
  73371. _this.exitVR();
  73372. if (!_this._useCustomVRButton) {
  73373. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  73374. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  73375. }
  73376. }
  73377. };
  73378. this.beforeRender = function () {
  73379. _this._castRayAndSelectObject();
  73380. };
  73381. this._onNewGamepadConnected = function (gamepad) {
  73382. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73383. if (gamepad.leftStick) {
  73384. gamepad.onleftstickchanged(function (stickValues) {
  73385. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  73386. // Listening to classic/xbox gamepad only if no VR controller is active
  73387. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  73388. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  73389. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  73390. _this._checkTeleportWithRay(stickValues);
  73391. _this._checkTeleportBackwards(stickValues);
  73392. }
  73393. }
  73394. });
  73395. }
  73396. if (gamepad.rightStick) {
  73397. gamepad.onrightstickchanged(function (stickValues) {
  73398. if (_this._teleportationInitialized) {
  73399. _this._checkRotate(stickValues);
  73400. }
  73401. });
  73402. }
  73403. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  73404. gamepad.onbuttondown(function (buttonPressed) {
  73405. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  73406. _this._selectionPointerDown();
  73407. }
  73408. });
  73409. gamepad.onbuttonup(function (buttonPressed) {
  73410. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  73411. _this._selectionPointerUp();
  73412. }
  73413. });
  73414. }
  73415. }
  73416. else {
  73417. var webVRController = gamepad;
  73418. _this._tryEnableInteractionOnController(webVRController);
  73419. }
  73420. };
  73421. // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded
  73422. this._tryEnableInteractionOnController = function (webVRController) {
  73423. if (webVRController.hand === "left") {
  73424. _this._leftControllerReady = true;
  73425. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  73426. _this._enableInteractionOnController(webVRController);
  73427. }
  73428. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  73429. _this._enableTeleportationOnController(webVRController);
  73430. }
  73431. }
  73432. if (webVRController.hand === "right") {
  73433. _this._rightControllerReady = true;
  73434. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  73435. _this._enableInteractionOnController(webVRController);
  73436. }
  73437. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  73438. _this._enableTeleportationOnController(webVRController);
  73439. }
  73440. }
  73441. };
  73442. this._onNewGamepadDisconnected = function (gamepad) {
  73443. if (gamepad instanceof BABYLON.WebVRController) {
  73444. if (gamepad.hand === "left") {
  73445. _this._interactionsEnabledOnLeftController = false;
  73446. _this._teleportationEnabledOnLeftController = false;
  73447. _this._leftControllerReady = false;
  73448. if (_this._leftLaserPointer) {
  73449. _this._leftLaserPointer.dispose();
  73450. }
  73451. }
  73452. if (gamepad.hand === "right") {
  73453. _this._interactionsEnabledOnRightController = false;
  73454. _this._teleportationEnabledOnRightController = false;
  73455. _this._rightControllerReady = false;
  73456. if (_this._rightLaserPointer) {
  73457. _this._rightLaserPointer.dispose();
  73458. }
  73459. }
  73460. }
  73461. };
  73462. this._workingVector = BABYLON.Vector3.Zero();
  73463. this._workingQuaternion = BABYLON.Quaternion.Identity();
  73464. this._workingMatrix = BABYLON.Matrix.Identity();
  73465. this._scene = scene;
  73466. this._canvas = scene.getEngine().getRenderingCanvas();
  73467. // Parse options
  73468. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  73469. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  73470. }
  73471. if (webVROptions.createDeviceOrientationCamera === undefined) {
  73472. webVROptions.createDeviceOrientationCamera = true;
  73473. }
  73474. if (webVROptions.defaultHeight === undefined) {
  73475. webVROptions.defaultHeight = 1.7;
  73476. }
  73477. if (webVROptions.useCustomVRButton) {
  73478. this._useCustomVRButton = true;
  73479. if (webVROptions.customVRButton) {
  73480. this._btnVR = webVROptions.customVRButton;
  73481. }
  73482. }
  73483. if (webVROptions.rayLength) {
  73484. this._rayLength = webVROptions.rayLength;
  73485. }
  73486. this._defaultHeight = webVROptions.defaultHeight;
  73487. // Set position
  73488. if (this._scene.activeCamera) {
  73489. this._position = this._scene.activeCamera.position.clone();
  73490. }
  73491. else {
  73492. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  73493. }
  73494. // Set non-vr camera
  73495. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  73496. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  73497. // Copy data from existing camera
  73498. if (this._scene.activeCamera) {
  73499. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  73500. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  73501. // Set rotation from previous camera
  73502. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  73503. var targetCamera = this._scene.activeCamera;
  73504. if (targetCamera.rotationQuaternion) {
  73505. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  73506. }
  73507. else {
  73508. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  73509. }
  73510. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  73511. }
  73512. }
  73513. this._scene.activeCamera = this._deviceOrientationCamera;
  73514. if (this._canvas) {
  73515. this._scene.activeCamera.attachControl(this._canvas);
  73516. }
  73517. }
  73518. else {
  73519. this._existingCamera = this._scene.activeCamera;
  73520. }
  73521. // Create VR cameras
  73522. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  73523. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  73524. }
  73525. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  73526. this._webVRCamera.useStandingMatrix();
  73527. // Create default button
  73528. if (!this._useCustomVRButton) {
  73529. this._btnVR = document.createElement("BUTTON");
  73530. this._btnVR.className = "babylonVRicon";
  73531. this._btnVR.id = "babylonVRiconbtn";
  73532. this._btnVR.title = "Click to switch to VR";
  73533. 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) }";
  73534. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  73535. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  73536. // css += ".babylonVRicon.vrdisplaysupported { }";
  73537. // css += ".babylonVRicon.vrdisplayready { }";
  73538. // css += ".babylonVRicon.vrdisplayrequesting { }";
  73539. var style = document.createElement('style');
  73540. style.appendChild(document.createTextNode(css));
  73541. document.getElementsByTagName('head')[0].appendChild(style);
  73542. this.moveButtonToBottomRight();
  73543. }
  73544. // VR button click event
  73545. if (this._btnVR) {
  73546. this._btnVR.addEventListener("click", function () {
  73547. if (!_this.isInVRMode) {
  73548. _this.enterVR();
  73549. }
  73550. else {
  73551. _this.exitVR();
  73552. }
  73553. });
  73554. }
  73555. // Window events
  73556. window.addEventListener("resize", this._onResize);
  73557. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  73558. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  73559. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  73560. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  73561. // Display vr button when headset is connected
  73562. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  73563. this.displayVRButton();
  73564. }
  73565. else {
  73566. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  73567. if (e.vrDisplay) {
  73568. _this.displayVRButton();
  73569. }
  73570. });
  73571. }
  73572. // Exiting VR mode using 'ESC' key on desktop
  73573. this._onKeyDown = function (event) {
  73574. if (event.keyCode === 27 && _this.isInVRMode) {
  73575. _this.exitVR();
  73576. }
  73577. };
  73578. document.addEventListener("keydown", this._onKeyDown);
  73579. // Exiting VR mode double tapping the touch screen
  73580. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  73581. if (_this.isInVRMode) {
  73582. _this.exitVR();
  73583. if (_this._fullscreenVRpresenting) {
  73584. _this._scene.getEngine().switchFullscreen(true);
  73585. }
  73586. }
  73587. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  73588. // Listen for WebVR display changes
  73589. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  73590. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  73591. this._onVRRequestPresentStart = function () {
  73592. _this._webVRrequesting = true;
  73593. _this.updateButtonVisibility();
  73594. };
  73595. this._onVRRequestPresentComplete = function (success) {
  73596. _this._webVRrequesting = false;
  73597. _this.updateButtonVisibility();
  73598. };
  73599. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  73600. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  73601. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  73602. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  73603. scene.onDisposeObservable.add(function () {
  73604. _this.dispose();
  73605. });
  73606. // Gamepad connection events
  73607. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  73608. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  73609. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  73610. this.updateButtonVisibility();
  73611. //create easing functions
  73612. this._circleEase = new BABYLON.CircleEase();
  73613. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  73614. }
  73615. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  73616. /** Return this.onEnteringVRObservable
  73617. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  73618. */
  73619. get: function () {
  73620. return this.onEnteringVRObservable;
  73621. },
  73622. enumerable: true,
  73623. configurable: true
  73624. });
  73625. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  73626. /** Return this.onExitingVRObservable
  73627. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  73628. */
  73629. get: function () {
  73630. return this.onExitingVRObservable;
  73631. },
  73632. enumerable: true,
  73633. configurable: true
  73634. });
  73635. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  73636. /** Return this.onControllerMeshLoadedObservable
  73637. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  73638. */
  73639. get: function () {
  73640. return this.onControllerMeshLoadedObservable;
  73641. },
  73642. enumerable: true,
  73643. configurable: true
  73644. });
  73645. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  73646. get: function () {
  73647. return this._teleportationTarget;
  73648. },
  73649. set: function (value) {
  73650. if (value) {
  73651. value.name = "teleportationTarget";
  73652. this._isDefaultTeleportationTarget = false;
  73653. this._teleportationTarget = value;
  73654. }
  73655. },
  73656. enumerable: true,
  73657. configurable: true
  73658. });
  73659. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  73660. get: function () {
  73661. return this._displayGaze;
  73662. },
  73663. set: function (value) {
  73664. this._displayGaze = value;
  73665. if (!value) {
  73666. this._gazeTracker.isVisible = false;
  73667. }
  73668. },
  73669. enumerable: true,
  73670. configurable: true
  73671. });
  73672. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  73673. get: function () {
  73674. return this._displayLaserPointer;
  73675. },
  73676. set: function (value) {
  73677. this._displayLaserPointer = value;
  73678. if (!value) {
  73679. if (this._rightLaserPointer) {
  73680. this._rightLaserPointer.isVisible = false;
  73681. }
  73682. if (this._leftLaserPointer) {
  73683. this._leftLaserPointer.isVisible = false;
  73684. }
  73685. }
  73686. else {
  73687. if (this._rightLaserPointer) {
  73688. this._rightLaserPointer.isVisible = true;
  73689. }
  73690. else if (this._leftLaserPointer) {
  73691. this._leftLaserPointer.isVisible = true;
  73692. }
  73693. }
  73694. },
  73695. enumerable: true,
  73696. configurable: true
  73697. });
  73698. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  73699. get: function () {
  73700. return this._deviceOrientationCamera;
  73701. },
  73702. enumerable: true,
  73703. configurable: true
  73704. });
  73705. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  73706. // Based on the current WebVR support, returns the current VR camera used
  73707. get: function () {
  73708. if (this._webVRready) {
  73709. return this._webVRCamera;
  73710. }
  73711. else {
  73712. return this._scene.activeCamera;
  73713. }
  73714. },
  73715. enumerable: true,
  73716. configurable: true
  73717. });
  73718. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  73719. get: function () {
  73720. return this._webVRCamera;
  73721. },
  73722. enumerable: true,
  73723. configurable: true
  73724. });
  73725. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  73726. get: function () {
  73727. return this._vrDeviceOrientationCamera;
  73728. },
  73729. enumerable: true,
  73730. configurable: true
  73731. });
  73732. // Raised when one of the controller has loaded successfully its associated default mesh
  73733. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  73734. this._tryEnableInteractionOnController(webVRController);
  73735. try {
  73736. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  73737. }
  73738. catch (err) {
  73739. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  73740. }
  73741. };
  73742. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  73743. /**
  73744. * Gets a value indicating if we are currently in VR mode.
  73745. */
  73746. get: function () {
  73747. return this._webVRpresenting || this._fullscreenVRpresenting;
  73748. },
  73749. enumerable: true,
  73750. configurable: true
  73751. });
  73752. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  73753. var vrDisplay = this._scene.getEngine().getVRDevice();
  73754. if (vrDisplay) {
  73755. var wasPresenting = this._webVRpresenting;
  73756. // A VR display is connected
  73757. this._webVRpresenting = vrDisplay.isPresenting;
  73758. if (wasPresenting && !this._webVRpresenting)
  73759. this.exitVR();
  73760. }
  73761. else {
  73762. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  73763. }
  73764. this.updateButtonVisibility();
  73765. };
  73766. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  73767. this._webVRsupported = eventArgs.vrSupported;
  73768. this._webVRready = !!eventArgs.vrDisplay;
  73769. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  73770. this.updateButtonVisibility();
  73771. };
  73772. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  73773. if (this._canvas && !this._useCustomVRButton) {
  73774. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  73775. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  73776. }
  73777. };
  73778. VRExperienceHelper.prototype.displayVRButton = function () {
  73779. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  73780. document.body.appendChild(this._btnVR);
  73781. this._btnVRDisplayed = true;
  73782. }
  73783. };
  73784. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  73785. if (!this._btnVR || this._useCustomVRButton) {
  73786. return;
  73787. }
  73788. this._btnVR.className = "babylonVRicon";
  73789. if (this.isInVRMode) {
  73790. this._btnVR.className += " vrdisplaypresenting";
  73791. }
  73792. else {
  73793. if (this._webVRready)
  73794. this._btnVR.className += " vrdisplayready";
  73795. if (this._webVRsupported)
  73796. this._btnVR.className += " vrdisplaysupported";
  73797. if (this._webVRrequesting)
  73798. this._btnVR.className += " vrdisplayrequesting";
  73799. }
  73800. };
  73801. /**
  73802. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  73803. * Otherwise, will use the fullscreen API.
  73804. */
  73805. VRExperienceHelper.prototype.enterVR = function () {
  73806. if (this.onEnteringVRObservable) {
  73807. try {
  73808. this.onEnteringVRObservable.notifyObservers(this);
  73809. }
  73810. catch (err) {
  73811. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  73812. }
  73813. }
  73814. if (this._scene.activeCamera) {
  73815. this._position = this._scene.activeCamera.position.clone();
  73816. // make sure that we return to the last active camera
  73817. this._existingCamera = this._scene.activeCamera;
  73818. }
  73819. if (this._webVRrequesting)
  73820. return;
  73821. // If WebVR is supported and a headset is connected
  73822. if (this._webVRready) {
  73823. if (!this._webVRpresenting) {
  73824. this._webVRCamera.position = this._position;
  73825. this._scene.activeCamera = this._webVRCamera;
  73826. }
  73827. }
  73828. else if (this._vrDeviceOrientationCamera) {
  73829. this._vrDeviceOrientationCamera.position = this._position;
  73830. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  73831. this._scene.getEngine().switchFullscreen(true);
  73832. this.updateButtonVisibility();
  73833. }
  73834. if (this._scene.activeCamera && this._canvas) {
  73835. this._scene.activeCamera.attachControl(this._canvas);
  73836. }
  73837. if (this._interactionsEnabled) {
  73838. this._scene.registerBeforeRender(this.beforeRender);
  73839. }
  73840. };
  73841. /**
  73842. * Attempt to exit VR, or fullscreen.
  73843. */
  73844. VRExperienceHelper.prototype.exitVR = function () {
  73845. if (this.onExitingVRObservable) {
  73846. try {
  73847. this.onExitingVRObservable.notifyObservers(this);
  73848. }
  73849. catch (err) {
  73850. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  73851. }
  73852. }
  73853. if (this._webVRpresenting) {
  73854. this._scene.getEngine().disableVR();
  73855. }
  73856. if (this._scene.activeCamera) {
  73857. this._position = this._scene.activeCamera.position.clone();
  73858. }
  73859. if (this._deviceOrientationCamera) {
  73860. this._deviceOrientationCamera.position = this._position;
  73861. this._scene.activeCamera = this._deviceOrientationCamera;
  73862. if (this._canvas) {
  73863. this._scene.activeCamera.attachControl(this._canvas);
  73864. }
  73865. }
  73866. else if (this._existingCamera) {
  73867. this._existingCamera.position = this._position;
  73868. this._scene.activeCamera = this._existingCamera;
  73869. }
  73870. this.updateButtonVisibility();
  73871. if (this._interactionsEnabled) {
  73872. this._scene.unregisterBeforeRender(this.beforeRender);
  73873. }
  73874. };
  73875. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  73876. get: function () {
  73877. return this._position;
  73878. },
  73879. set: function (value) {
  73880. this._position = value;
  73881. if (this._scene.activeCamera) {
  73882. this._scene.activeCamera.position = value;
  73883. }
  73884. },
  73885. enumerable: true,
  73886. configurable: true
  73887. });
  73888. VRExperienceHelper.prototype.enableInteractions = function () {
  73889. var _this = this;
  73890. if (!this._interactionsEnabled) {
  73891. this._interactionsRequested = true;
  73892. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73893. this._enableInteractionOnController(this._webVRCamera.leftController);
  73894. }
  73895. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73896. this._enableInteractionOnController(this._webVRCamera.rightController);
  73897. }
  73898. this._createGazeTracker();
  73899. this.raySelectionPredicate = function (mesh) {
  73900. return mesh.isVisible;
  73901. };
  73902. this.meshSelectionPredicate = function (mesh) {
  73903. return true;
  73904. };
  73905. this._raySelectionPredicate = function (mesh) {
  73906. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  73907. && mesh.name.indexOf("teleportationTarget") === -1
  73908. && mesh.name.indexOf("torusTeleportation") === -1
  73909. && mesh.name.indexOf("laserPointer") === -1)) {
  73910. return _this.raySelectionPredicate(mesh);
  73911. }
  73912. return false;
  73913. };
  73914. this._interactionsEnabled = true;
  73915. }
  73916. };
  73917. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  73918. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  73919. if (this._floorMeshesCollection[i].id === mesh.id) {
  73920. return true;
  73921. }
  73922. }
  73923. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  73924. return true;
  73925. }
  73926. return false;
  73927. };
  73928. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  73929. if (!this._floorMeshesCollection) {
  73930. return;
  73931. }
  73932. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  73933. return;
  73934. }
  73935. this._floorMeshesCollection.push(floorMesh);
  73936. };
  73937. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  73938. if (!this._floorMeshesCollection) {
  73939. return;
  73940. }
  73941. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  73942. if (meshIndex !== -1) {
  73943. this._floorMeshesCollection.splice(meshIndex, 1);
  73944. }
  73945. };
  73946. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  73947. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  73948. if (!this._teleportationInitialized) {
  73949. this._teleportationRequested = true;
  73950. this.enableInteractions();
  73951. if (vrTeleportationOptions.floorMeshName) {
  73952. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  73953. }
  73954. if (vrTeleportationOptions.floorMeshes) {
  73955. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  73956. }
  73957. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73958. this._enableTeleportationOnController(this._webVRCamera.leftController);
  73959. }
  73960. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73961. this._enableTeleportationOnController(this._webVRCamera.rightController);
  73962. }
  73963. // Creates an image processing post process for the vignette not relying
  73964. // on the main scene configuration for image processing to reduce setup and spaces
  73965. // (gamma/linear) conflicts.
  73966. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  73967. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  73968. imageProcessingConfiguration.vignetteEnabled = true;
  73969. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  73970. this._webVRCamera.detachPostProcess(this._postProcessMove);
  73971. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  73972. this._teleportationInitialized = true;
  73973. if (this._isDefaultTeleportationTarget) {
  73974. this._createTeleportationCircles();
  73975. }
  73976. }
  73977. };
  73978. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  73979. var _this = this;
  73980. var controllerMesh = webVRController.mesh;
  73981. if (controllerMesh) {
  73982. var makeNotPick = function (root) {
  73983. root.name += " laserPointer";
  73984. root.getChildMeshes().forEach(function (c) {
  73985. makeNotPick(c);
  73986. });
  73987. };
  73988. makeNotPick(controllerMesh);
  73989. var childMeshes = controllerMesh.getChildMeshes();
  73990. for (var i = 0; i < childMeshes.length; i++) {
  73991. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  73992. controllerMesh = childMeshes[i];
  73993. break;
  73994. }
  73995. }
  73996. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  73997. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  73998. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  73999. laserPointerMaterial.alpha = 0.6;
  74000. laserPointer.material = laserPointerMaterial;
  74001. laserPointer.rotation.x = Math.PI / 2;
  74002. laserPointer.parent = controllerMesh;
  74003. laserPointer.position.z = -0.5;
  74004. laserPointer.isVisible = false;
  74005. if (webVRController.hand === "left") {
  74006. this._leftLaserPointer = laserPointer;
  74007. this._interactionsEnabledOnLeftController = true;
  74008. if (!this._rightLaserPointer) {
  74009. this._leftLaserPointer.isVisible = true;
  74010. }
  74011. }
  74012. else {
  74013. this._rightLaserPointer = laserPointer;
  74014. this._interactionsEnabledOnRightController = true;
  74015. if (!this._leftLaserPointer) {
  74016. this._rightLaserPointer.isVisible = true;
  74017. }
  74018. }
  74019. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  74020. // Enabling / disabling laserPointer
  74021. if (_this._displayLaserPointer && stateObject.value === 1) {
  74022. laserPointer.isVisible = !laserPointer.isVisible;
  74023. // Laser pointer can only be active on left or right, not both at the same time
  74024. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  74025. _this._rightLaserPointer.isVisible = false;
  74026. }
  74027. else if (_this._leftLaserPointer) {
  74028. _this._leftLaserPointer.isVisible = false;
  74029. }
  74030. }
  74031. });
  74032. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  74033. if (!_this._pointerDownOnMeshAsked) {
  74034. if (stateObject.value > _this._padSensibilityUp) {
  74035. _this._selectionPointerDown();
  74036. }
  74037. }
  74038. else if (stateObject.value < _this._padSensibilityDown) {
  74039. _this._selectionPointerUp();
  74040. }
  74041. });
  74042. }
  74043. };
  74044. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  74045. if (webVRController === void 0) { webVRController = null; }
  74046. if (!this._teleportationRequestInitiated) {
  74047. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  74048. if (webVRController) {
  74049. // If laser pointer wasn't enabled yet
  74050. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  74051. this._leftLaserPointer.isVisible = true;
  74052. if (this._rightLaserPointer) {
  74053. this._rightLaserPointer.isVisible = false;
  74054. }
  74055. }
  74056. else if (this._displayLaserPointer && this._rightLaserPointer) {
  74057. this._rightLaserPointer.isVisible = true;
  74058. if (this._leftLaserPointer) {
  74059. this._leftLaserPointer.isVisible = false;
  74060. }
  74061. }
  74062. }
  74063. this._teleportationRequestInitiated = true;
  74064. }
  74065. }
  74066. else {
  74067. // Listening to the proper controller values changes to confirm teleportation
  74068. if (webVRController == null
  74069. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  74070. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  74071. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  74072. if (this._teleportationAllowed) {
  74073. this._teleportationAllowed = false;
  74074. this._teleportCamera();
  74075. }
  74076. this._teleportationRequestInitiated = false;
  74077. }
  74078. }
  74079. }
  74080. };
  74081. VRExperienceHelper.prototype._selectionPointerDown = function () {
  74082. this._pointerDownOnMeshAsked = true;
  74083. if (this._currentMeshSelected && this._currentHit) {
  74084. this._scene.simulatePointerDown(this._currentHit);
  74085. }
  74086. };
  74087. VRExperienceHelper.prototype._selectionPointerUp = function () {
  74088. if (this._currentMeshSelected && this._currentHit) {
  74089. this._scene.simulatePointerUp(this._currentHit);
  74090. }
  74091. this._pointerDownOnMeshAsked = false;
  74092. };
  74093. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  74094. // Only rotate when user is not currently selecting a teleportation location
  74095. if (this._teleportationRequestInitiated) {
  74096. return;
  74097. }
  74098. if (!this._rotationLeftAsked) {
  74099. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  74100. this._rotationLeftAsked = true;
  74101. if (this._rotationAllowed) {
  74102. this._rotateCamera(false);
  74103. }
  74104. }
  74105. }
  74106. else {
  74107. if (stateObject.x > -this._padSensibilityDown) {
  74108. this._rotationLeftAsked = false;
  74109. }
  74110. }
  74111. if (!this._rotationRightAsked) {
  74112. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  74113. this._rotationRightAsked = true;
  74114. if (this._rotationAllowed) {
  74115. this._rotateCamera(true);
  74116. }
  74117. }
  74118. }
  74119. else {
  74120. if (stateObject.x < this._padSensibilityDown) {
  74121. this._rotationRightAsked = false;
  74122. }
  74123. }
  74124. };
  74125. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  74126. // Only teleport backwards when user is not currently selecting a teleportation location
  74127. if (this._teleportationRequestInitiated) {
  74128. return;
  74129. }
  74130. // Teleport backwards
  74131. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  74132. if (!this._teleportationBackRequestInitiated) {
  74133. if (!this.currentVRCamera) {
  74134. return;
  74135. }
  74136. // Get rotation and position of the current camera
  74137. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  74138. var position = this.currentVRCamera.position;
  74139. // If the camera has device position, use that instead
  74140. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  74141. rotation = this.currentVRCamera.deviceRotationQuaternion;
  74142. position = this.currentVRCamera.devicePosition;
  74143. }
  74144. // Get matrix with only the y rotation of the device rotation
  74145. rotation.toEulerAnglesToRef(this._workingVector);
  74146. this._workingVector.z = 0;
  74147. this._workingVector.x = 0;
  74148. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  74149. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  74150. // Rotate backwards ray by device rotation to cast at the ground behind the user
  74151. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  74152. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  74153. var ray = new BABYLON.Ray(position, this._workingVector);
  74154. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  74155. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  74156. this._teleportCamera(hit.pickedPoint);
  74157. }
  74158. this._teleportationBackRequestInitiated = true;
  74159. }
  74160. }
  74161. else {
  74162. this._teleportationBackRequestInitiated = false;
  74163. }
  74164. };
  74165. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  74166. var _this = this;
  74167. var controllerMesh = webVRController.mesh;
  74168. if (controllerMesh) {
  74169. if (webVRController.hand === "left") {
  74170. if (!this._interactionsEnabledOnLeftController) {
  74171. this._enableInteractionOnController(webVRController);
  74172. }
  74173. this._teleportationEnabledOnLeftController = true;
  74174. }
  74175. else {
  74176. if (!this._interactionsEnabledOnRightController) {
  74177. this._enableInteractionOnController(webVRController);
  74178. }
  74179. this._teleportationEnabledOnRightController = true;
  74180. }
  74181. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  74182. this._dpadPressed = false;
  74183. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  74184. _this._dpadPressed = stateObject.pressed;
  74185. if (!_this._dpadPressed) {
  74186. _this._rotationLeftAsked = false;
  74187. _this._rotationRightAsked = false;
  74188. _this._teleportationBackRequestInitiated = false;
  74189. }
  74190. });
  74191. }
  74192. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  74193. if (_this.teleportationEnabled) {
  74194. _this._checkTeleportBackwards(stateObject);
  74195. _this._checkTeleportWithRay(stateObject, webVRController);
  74196. }
  74197. _this._checkRotate(stateObject);
  74198. });
  74199. }
  74200. };
  74201. // Gaze support used to point to teleport or to interact with an object
  74202. VRExperienceHelper.prototype._createGazeTracker = function () {
  74203. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  74204. this._gazeTracker.bakeCurrentTransformIntoVertices();
  74205. this._gazeTracker.isPickable = false;
  74206. this._gazeTracker.isVisible = false;
  74207. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  74208. targetMat.specularColor = BABYLON.Color3.Black();
  74209. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  74210. targetMat.backFaceCulling = false;
  74211. this._gazeTracker.material = targetMat;
  74212. };
  74213. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  74214. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  74215. this._teleportationTarget.isPickable = false;
  74216. var length = 512;
  74217. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  74218. dynamicTexture.hasAlpha = true;
  74219. var context = dynamicTexture.getContext();
  74220. var centerX = length / 2;
  74221. var centerY = length / 2;
  74222. var radius = 200;
  74223. context.beginPath();
  74224. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  74225. context.fillStyle = this._teleportationFillColor;
  74226. context.fill();
  74227. context.lineWidth = 10;
  74228. context.strokeStyle = this._teleportationBorderColor;
  74229. context.stroke();
  74230. context.closePath();
  74231. dynamicTexture.update();
  74232. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  74233. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  74234. this._teleportationTarget.material = teleportationCircleMaterial;
  74235. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  74236. torus.isPickable = false;
  74237. torus.parent = this._teleportationTarget;
  74238. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  74239. var keys = [];
  74240. keys.push({
  74241. frame: 0,
  74242. value: 0
  74243. });
  74244. keys.push({
  74245. frame: 30,
  74246. value: 0.4
  74247. });
  74248. keys.push({
  74249. frame: 60,
  74250. value: 0
  74251. });
  74252. animationInnerCircle.setKeys(keys);
  74253. var easingFunction = new BABYLON.SineEase();
  74254. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  74255. animationInnerCircle.setEasingFunction(easingFunction);
  74256. torus.animations = [];
  74257. torus.animations.push(animationInnerCircle);
  74258. this._scene.beginAnimation(torus, 0, 60, true);
  74259. this._hideTeleportationTarget();
  74260. };
  74261. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  74262. if (this._teleportationInitialized) {
  74263. this._teleportationTarget.isVisible = true;
  74264. if (this._isDefaultTeleportationTarget) {
  74265. this._teleportationTarget.getChildren()[0].isVisible = true;
  74266. }
  74267. }
  74268. };
  74269. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  74270. if (this._teleportationInitialized) {
  74271. this._teleportationTarget.isVisible = false;
  74272. if (this._isDefaultTeleportationTarget) {
  74273. this._teleportationTarget.getChildren()[0].isVisible = false;
  74274. }
  74275. }
  74276. };
  74277. VRExperienceHelper.prototype._rotateCamera = function (right) {
  74278. var _this = this;
  74279. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74280. return;
  74281. }
  74282. if (right) {
  74283. this._rotationAngle++;
  74284. }
  74285. else {
  74286. this._rotationAngle--;
  74287. }
  74288. this.currentVRCamera.animations = [];
  74289. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  74290. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74291. var animationRotationKeys = [];
  74292. animationRotationKeys.push({
  74293. frame: 0,
  74294. value: this.currentVRCamera.rotationQuaternion
  74295. });
  74296. animationRotationKeys.push({
  74297. frame: 6,
  74298. value: target
  74299. });
  74300. animationRotation.setKeys(animationRotationKeys);
  74301. animationRotation.setEasingFunction(this._circleEase);
  74302. this.currentVRCamera.animations.push(animationRotation);
  74303. this._postProcessMove.animations = [];
  74304. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74305. var vignetteWeightKeys = [];
  74306. vignetteWeightKeys.push({
  74307. frame: 0,
  74308. value: 0
  74309. });
  74310. vignetteWeightKeys.push({
  74311. frame: 3,
  74312. value: 4
  74313. });
  74314. vignetteWeightKeys.push({
  74315. frame: 6,
  74316. value: 0
  74317. });
  74318. animationPP.setKeys(vignetteWeightKeys);
  74319. animationPP.setEasingFunction(this._circleEase);
  74320. this._postProcessMove.animations.push(animationPP);
  74321. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74322. var vignetteStretchKeys = [];
  74323. vignetteStretchKeys.push({
  74324. frame: 0,
  74325. value: 0
  74326. });
  74327. vignetteStretchKeys.push({
  74328. frame: 3,
  74329. value: 10
  74330. });
  74331. vignetteStretchKeys.push({
  74332. frame: 6,
  74333. value: 0
  74334. });
  74335. animationPP2.setKeys(vignetteStretchKeys);
  74336. animationPP2.setEasingFunction(this._circleEase);
  74337. this._postProcessMove.animations.push(animationPP2);
  74338. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  74339. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  74340. this._webVRCamera.attachPostProcess(this._postProcessMove);
  74341. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  74342. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  74343. });
  74344. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  74345. };
  74346. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  74347. if (hit.pickedPoint) {
  74348. this._teleportationAllowed = true;
  74349. if (this._teleportationRequestInitiated) {
  74350. this._displayTeleportationTarget();
  74351. }
  74352. else {
  74353. this._hideTeleportationTarget();
  74354. }
  74355. this._haloCenter.copyFrom(hit.pickedPoint);
  74356. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  74357. var pickNormal = hit.getNormal(true, false);
  74358. if (pickNormal) {
  74359. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  74360. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  74361. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  74362. }
  74363. this._teleportationTarget.position.y += 0.1;
  74364. }
  74365. };
  74366. VRExperienceHelper.prototype._teleportCamera = function (location) {
  74367. var _this = this;
  74368. if (location === void 0) { location = null; }
  74369. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74370. return;
  74371. }
  74372. if (!location) {
  74373. location = this._haloCenter;
  74374. }
  74375. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  74376. // offset of the headset from the anchor.
  74377. if (this.webVRCamera.leftCamera) {
  74378. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  74379. this._workingVector.subtractInPlace(this.webVRCamera.position);
  74380. location.subtractToRef(this._workingVector, this._workingVector);
  74381. }
  74382. else {
  74383. this._workingVector.copyFrom(location);
  74384. }
  74385. // Add height to account for user's height offset
  74386. if (this.isInVRMode) {
  74387. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  74388. }
  74389. else {
  74390. this._workingVector.y += this._defaultHeight;
  74391. }
  74392. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  74393. // Create animation from the camera's position to the new location
  74394. this.currentVRCamera.animations = [];
  74395. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74396. var animationCameraTeleportationKeys = [{
  74397. frame: 0,
  74398. value: this.currentVRCamera.position
  74399. },
  74400. {
  74401. frame: 11,
  74402. value: this._workingVector
  74403. }
  74404. ];
  74405. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  74406. animationCameraTeleportation.setEasingFunction(this._circleEase);
  74407. this.currentVRCamera.animations.push(animationCameraTeleportation);
  74408. this._postProcessMove.animations = [];
  74409. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74410. var vignetteWeightKeys = [];
  74411. vignetteWeightKeys.push({
  74412. frame: 0,
  74413. value: 0
  74414. });
  74415. vignetteWeightKeys.push({
  74416. frame: 5,
  74417. value: 8
  74418. });
  74419. vignetteWeightKeys.push({
  74420. frame: 11,
  74421. value: 0
  74422. });
  74423. animationPP.setKeys(vignetteWeightKeys);
  74424. this._postProcessMove.animations.push(animationPP);
  74425. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74426. var vignetteStretchKeys = [];
  74427. vignetteStretchKeys.push({
  74428. frame: 0,
  74429. value: 0
  74430. });
  74431. vignetteStretchKeys.push({
  74432. frame: 5,
  74433. value: 10
  74434. });
  74435. vignetteStretchKeys.push({
  74436. frame: 11,
  74437. value: 0
  74438. });
  74439. animationPP2.setKeys(vignetteStretchKeys);
  74440. this._postProcessMove.animations.push(animationPP2);
  74441. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  74442. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  74443. this._webVRCamera.attachPostProcess(this._postProcessMove);
  74444. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  74445. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  74446. });
  74447. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  74448. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  74449. });
  74450. };
  74451. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  74452. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74453. return;
  74454. }
  74455. var ray;
  74456. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  74457. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  74458. }
  74459. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  74460. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  74461. }
  74462. else {
  74463. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  74464. }
  74465. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  74466. // Moving the gazeTracker on the mesh face targetted
  74467. if (hit && hit.pickedPoint) {
  74468. if (this._displayGaze) {
  74469. var multiplier = 1;
  74470. this._gazeTracker.isVisible = true;
  74471. if (this._isActionableMesh) {
  74472. multiplier = 3;
  74473. }
  74474. this._gazeTracker.scaling.x = hit.distance * multiplier;
  74475. this._gazeTracker.scaling.y = hit.distance * multiplier;
  74476. this._gazeTracker.scaling.z = hit.distance * multiplier;
  74477. var pickNormal = hit.getNormal();
  74478. // To avoid z-fighting
  74479. var deltaFighting = 0.002;
  74480. if (pickNormal) {
  74481. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  74482. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  74483. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  74484. }
  74485. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  74486. if (this._gazeTracker.position.x < 0) {
  74487. this._gazeTracker.position.x += deltaFighting;
  74488. }
  74489. else {
  74490. this._gazeTracker.position.x -= deltaFighting;
  74491. }
  74492. if (this._gazeTracker.position.y < 0) {
  74493. this._gazeTracker.position.y += deltaFighting;
  74494. }
  74495. else {
  74496. this._gazeTracker.position.y -= deltaFighting;
  74497. }
  74498. if (this._gazeTracker.position.z < 0) {
  74499. this._gazeTracker.position.z += deltaFighting;
  74500. }
  74501. else {
  74502. this._gazeTracker.position.z -= deltaFighting;
  74503. }
  74504. }
  74505. // Changing the size of the laser pointer based on the distance from the targetted point
  74506. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  74507. this._rightLaserPointer.scaling.y = hit.distance;
  74508. this._rightLaserPointer.position.z = -hit.distance / 2;
  74509. }
  74510. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  74511. this._leftLaserPointer.scaling.y = hit.distance;
  74512. this._leftLaserPointer.position.z = -hit.distance / 2;
  74513. }
  74514. }
  74515. else {
  74516. this._gazeTracker.isVisible = false;
  74517. }
  74518. if (hit && hit.pickedMesh) {
  74519. this._currentHit = hit;
  74520. if (this._pointerDownOnMeshAsked) {
  74521. this._scene.simulatePointerMove(this._currentHit);
  74522. }
  74523. // The object selected is the floor, we're in a teleportation scenario
  74524. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  74525. // Moving the teleportation area to this targetted point
  74526. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  74527. if (this._currentMeshSelected &&
  74528. !this._isTeleportationFloor(this._currentMeshSelected)) {
  74529. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  74530. }
  74531. this._currentMeshSelected = null;
  74532. this._moveTeleportationSelectorTo(hit);
  74533. return;
  74534. }
  74535. // If not, we're in a selection scenario
  74536. this._hideTeleportationTarget();
  74537. this._teleportationAllowed = false;
  74538. if (hit.pickedMesh !== this._currentMeshSelected) {
  74539. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  74540. this.onNewMeshPicked.notifyObservers(hit);
  74541. this._currentMeshSelected = hit.pickedMesh;
  74542. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  74543. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  74544. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  74545. this._isActionableMesh = true;
  74546. }
  74547. else {
  74548. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74549. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74550. this._isActionableMesh = false;
  74551. }
  74552. try {
  74553. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  74554. }
  74555. catch (err) {
  74556. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  74557. }
  74558. }
  74559. else {
  74560. if (this._currentMeshSelected) {
  74561. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  74562. }
  74563. this._currentMeshSelected = null;
  74564. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74565. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74566. }
  74567. }
  74568. }
  74569. else {
  74570. this._currentHit = null;
  74571. this._currentMeshSelected = null;
  74572. this._teleportationAllowed = false;
  74573. this._hideTeleportationTarget();
  74574. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74575. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74576. }
  74577. };
  74578. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  74579. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  74580. this._leftLaserPointer.material.emissiveColor = color;
  74581. }
  74582. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  74583. this._rightLaserPointer.material.emissiveColor = color;
  74584. }
  74585. };
  74586. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  74587. if (this._gazeTracker.material) {
  74588. this._gazeTracker.material.emissiveColor = color;
  74589. }
  74590. };
  74591. VRExperienceHelper.prototype.dispose = function () {
  74592. if (this.isInVRMode) {
  74593. this.exitVR();
  74594. }
  74595. if (this._passProcessMove) {
  74596. this._passProcessMove.dispose();
  74597. }
  74598. if (this._postProcessMove) {
  74599. this._postProcessMove.dispose();
  74600. }
  74601. if (this._webVRCamera) {
  74602. this._webVRCamera.dispose();
  74603. }
  74604. if (this._vrDeviceOrientationCamera) {
  74605. this._vrDeviceOrientationCamera.dispose();
  74606. }
  74607. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  74608. document.body.removeChild(this._btnVR);
  74609. }
  74610. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  74611. this._deviceOrientationCamera.dispose();
  74612. }
  74613. if (this._gazeTracker) {
  74614. this._gazeTracker.dispose();
  74615. }
  74616. if (this._teleportationTarget) {
  74617. this._teleportationTarget.dispose();
  74618. }
  74619. this._floorMeshesCollection = [];
  74620. document.removeEventListener("keydown", this._onKeyDown);
  74621. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74622. window.removeEventListener("resize", this._onResize);
  74623. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  74624. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  74625. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  74626. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  74627. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  74628. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  74629. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  74630. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74631. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  74632. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  74633. this._scene.unregisterBeforeRender(this.beforeRender);
  74634. };
  74635. VRExperienceHelper.prototype.getClassName = function () {
  74636. return "VRExperienceHelper";
  74637. };
  74638. return VRExperienceHelper;
  74639. }());
  74640. BABYLON.VRExperienceHelper = VRExperienceHelper;
  74641. })(BABYLON || (BABYLON = {}));
  74642. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  74643. // Mainly based on these 2 articles :
  74644. // 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
  74645. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  74646. var BABYLON;
  74647. (function (BABYLON) {
  74648. var JoystickAxis;
  74649. (function (JoystickAxis) {
  74650. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  74651. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  74652. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  74653. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  74654. var VirtualJoystick = /** @class */ (function () {
  74655. function VirtualJoystick(leftJoystick) {
  74656. var _this = this;
  74657. if (leftJoystick) {
  74658. this._leftJoystick = true;
  74659. }
  74660. else {
  74661. this._leftJoystick = false;
  74662. }
  74663. VirtualJoystick._globalJoystickIndex++;
  74664. // By default left & right arrow keys are moving the X
  74665. // and up & down keys are moving the Y
  74666. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74667. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74668. this.reverseLeftRight = false;
  74669. this.reverseUpDown = false;
  74670. // collections of pointers
  74671. this._touches = new BABYLON.StringDictionary();
  74672. this.deltaPosition = BABYLON.Vector3.Zero();
  74673. this._joystickSensibility = 25;
  74674. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74675. this._onResize = function (evt) {
  74676. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74677. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74678. if (VirtualJoystick.vjCanvas) {
  74679. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  74680. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  74681. }
  74682. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  74683. };
  74684. // injecting a canvas element on top of the canvas 3D game
  74685. if (!VirtualJoystick.vjCanvas) {
  74686. window.addEventListener("resize", this._onResize, false);
  74687. VirtualJoystick.vjCanvas = document.createElement("canvas");
  74688. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74689. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74690. VirtualJoystick.vjCanvas.width = window.innerWidth;
  74691. VirtualJoystick.vjCanvas.height = window.innerHeight;
  74692. VirtualJoystick.vjCanvas.style.width = "100%";
  74693. VirtualJoystick.vjCanvas.style.height = "100%";
  74694. VirtualJoystick.vjCanvas.style.position = "absolute";
  74695. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  74696. VirtualJoystick.vjCanvas.style.top = "0px";
  74697. VirtualJoystick.vjCanvas.style.left = "0px";
  74698. VirtualJoystick.vjCanvas.style.zIndex = "5";
  74699. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  74700. // Support for jQuery PEP polyfill
  74701. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  74702. var context = VirtualJoystick.vjCanvas.getContext('2d');
  74703. if (!context) {
  74704. throw new Error("Unable to create canvas for virtual joystick");
  74705. }
  74706. VirtualJoystick.vjCanvasContext = context;
  74707. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  74708. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74709. document.body.appendChild(VirtualJoystick.vjCanvas);
  74710. }
  74711. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  74712. this.pressed = false;
  74713. // default joystick color
  74714. this._joystickColor = "cyan";
  74715. this._joystickPointerID = -1;
  74716. // current joystick position
  74717. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  74718. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  74719. // origin joystick position
  74720. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  74721. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  74722. this._onPointerDownHandlerRef = function (evt) {
  74723. _this._onPointerDown(evt);
  74724. };
  74725. this._onPointerMoveHandlerRef = function (evt) {
  74726. _this._onPointerMove(evt);
  74727. };
  74728. this._onPointerUpHandlerRef = function (evt) {
  74729. _this._onPointerUp(evt);
  74730. };
  74731. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  74732. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  74733. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  74734. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  74735. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  74736. evt.preventDefault(); // Disables system menu
  74737. }, false);
  74738. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74739. }
  74740. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  74741. this._joystickSensibility = newJoystickSensibility;
  74742. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74743. };
  74744. VirtualJoystick.prototype._onPointerDown = function (e) {
  74745. var positionOnScreenCondition;
  74746. e.preventDefault();
  74747. if (this._leftJoystick === true) {
  74748. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  74749. }
  74750. else {
  74751. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  74752. }
  74753. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  74754. // First contact will be dedicated to the virtual joystick
  74755. this._joystickPointerID = e.pointerId;
  74756. this._joystickPointerStartPos.x = e.clientX;
  74757. this._joystickPointerStartPos.y = e.clientY;
  74758. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  74759. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  74760. this._deltaJoystickVector.x = 0;
  74761. this._deltaJoystickVector.y = 0;
  74762. this.pressed = true;
  74763. this._touches.add(e.pointerId.toString(), e);
  74764. }
  74765. else {
  74766. // You can only trigger the action buttons with a joystick declared
  74767. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  74768. this._action();
  74769. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  74770. }
  74771. }
  74772. };
  74773. VirtualJoystick.prototype._onPointerMove = function (e) {
  74774. // If the current pointer is the one associated to the joystick (first touch contact)
  74775. if (this._joystickPointerID == e.pointerId) {
  74776. this._joystickPointerPos.x = e.clientX;
  74777. this._joystickPointerPos.y = e.clientY;
  74778. this._deltaJoystickVector = this._joystickPointerPos.clone();
  74779. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  74780. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  74781. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  74782. switch (this._axisTargetedByLeftAndRight) {
  74783. case JoystickAxis.X:
  74784. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  74785. break;
  74786. case JoystickAxis.Y:
  74787. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  74788. break;
  74789. case JoystickAxis.Z:
  74790. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  74791. break;
  74792. }
  74793. var directionUpDown = this.reverseUpDown ? 1 : -1;
  74794. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  74795. switch (this._axisTargetedByUpAndDown) {
  74796. case JoystickAxis.X:
  74797. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  74798. break;
  74799. case JoystickAxis.Y:
  74800. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  74801. break;
  74802. case JoystickAxis.Z:
  74803. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  74804. break;
  74805. }
  74806. }
  74807. else {
  74808. var data = this._touches.get(e.pointerId.toString());
  74809. if (data) {
  74810. data.x = e.clientX;
  74811. data.y = e.clientY;
  74812. }
  74813. }
  74814. };
  74815. VirtualJoystick.prototype._onPointerUp = function (e) {
  74816. if (this._joystickPointerID == e.pointerId) {
  74817. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  74818. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  74819. this._joystickPointerID = -1;
  74820. this.pressed = false;
  74821. }
  74822. else {
  74823. var touch = this._touches.get(e.pointerId.toString());
  74824. if (touch) {
  74825. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74826. }
  74827. }
  74828. this._deltaJoystickVector.x = 0;
  74829. this._deltaJoystickVector.y = 0;
  74830. this._touches.remove(e.pointerId.toString());
  74831. };
  74832. /**
  74833. * Change the color of the virtual joystick
  74834. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  74835. */
  74836. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  74837. this._joystickColor = newColor;
  74838. };
  74839. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  74840. this._action = action;
  74841. };
  74842. // Define which axis you'd like to control for left & right
  74843. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  74844. switch (axis) {
  74845. case JoystickAxis.X:
  74846. case JoystickAxis.Y:
  74847. case JoystickAxis.Z:
  74848. this._axisTargetedByLeftAndRight = axis;
  74849. break;
  74850. default:
  74851. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74852. break;
  74853. }
  74854. };
  74855. // Define which axis you'd like to control for up & down
  74856. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  74857. switch (axis) {
  74858. case JoystickAxis.X:
  74859. case JoystickAxis.Y:
  74860. case JoystickAxis.Z:
  74861. this._axisTargetedByUpAndDown = axis;
  74862. break;
  74863. default:
  74864. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74865. break;
  74866. }
  74867. };
  74868. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  74869. var _this = this;
  74870. if (this.pressed) {
  74871. this._touches.forEach(function (key, touch) {
  74872. if (touch.pointerId === _this._joystickPointerID) {
  74873. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  74874. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  74875. VirtualJoystick.vjCanvasContext.beginPath();
  74876. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74877. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74878. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  74879. VirtualJoystick.vjCanvasContext.stroke();
  74880. VirtualJoystick.vjCanvasContext.closePath();
  74881. VirtualJoystick.vjCanvasContext.beginPath();
  74882. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74883. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74884. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  74885. VirtualJoystick.vjCanvasContext.stroke();
  74886. VirtualJoystick.vjCanvasContext.closePath();
  74887. VirtualJoystick.vjCanvasContext.beginPath();
  74888. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74889. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  74890. VirtualJoystick.vjCanvasContext.stroke();
  74891. VirtualJoystick.vjCanvasContext.closePath();
  74892. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  74893. }
  74894. else {
  74895. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74896. VirtualJoystick.vjCanvasContext.beginPath();
  74897. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  74898. VirtualJoystick.vjCanvasContext.beginPath();
  74899. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  74900. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74901. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  74902. VirtualJoystick.vjCanvasContext.stroke();
  74903. VirtualJoystick.vjCanvasContext.closePath();
  74904. touch.prevX = touch.x;
  74905. touch.prevY = touch.y;
  74906. }
  74907. ;
  74908. });
  74909. }
  74910. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74911. };
  74912. VirtualJoystick.prototype.releaseCanvas = function () {
  74913. if (VirtualJoystick.vjCanvas) {
  74914. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  74915. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  74916. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  74917. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  74918. window.removeEventListener("resize", this._onResize);
  74919. document.body.removeChild(VirtualJoystick.vjCanvas);
  74920. VirtualJoystick.vjCanvas = null;
  74921. }
  74922. };
  74923. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  74924. VirtualJoystick._globalJoystickIndex = 0;
  74925. return VirtualJoystick;
  74926. }());
  74927. BABYLON.VirtualJoystick = VirtualJoystick;
  74928. })(BABYLON || (BABYLON = {}));
  74929. //# sourceMappingURL=babylon.virtualJoystick.js.map
  74930. var BABYLON;
  74931. (function (BABYLON) {
  74932. // We're mainly based on the logic defined into the FreeCamera code
  74933. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  74934. __extends(VirtualJoysticksCamera, _super);
  74935. function VirtualJoysticksCamera(name, position, scene) {
  74936. var _this = _super.call(this, name, position, scene) || this;
  74937. _this.inputs.addVirtualJoystick();
  74938. return _this;
  74939. }
  74940. VirtualJoysticksCamera.prototype.getClassName = function () {
  74941. return "VirtualJoysticksCamera";
  74942. };
  74943. return VirtualJoysticksCamera;
  74944. }(BABYLON.FreeCamera));
  74945. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  74946. })(BABYLON || (BABYLON = {}));
  74947. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  74948. var BABYLON;
  74949. (function (BABYLON) {
  74950. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  74951. function FreeCameraVirtualJoystickInput() {
  74952. }
  74953. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  74954. return this._leftjoystick;
  74955. };
  74956. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  74957. return this._rightjoystick;
  74958. };
  74959. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  74960. if (this._leftjoystick) {
  74961. var camera = this.camera;
  74962. var speed = camera._computeLocalCameraSpeed() * 50;
  74963. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  74964. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  74965. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  74966. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  74967. if (!this._leftjoystick.pressed) {
  74968. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  74969. }
  74970. if (!this._rightjoystick.pressed) {
  74971. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  74972. }
  74973. }
  74974. };
  74975. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  74976. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  74977. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  74978. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  74979. this._leftjoystick.setJoystickSensibility(0.15);
  74980. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  74981. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  74982. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  74983. this._rightjoystick.reverseUpDown = true;
  74984. this._rightjoystick.setJoystickSensibility(0.05);
  74985. this._rightjoystick.setJoystickColor("yellow");
  74986. };
  74987. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  74988. this._leftjoystick.releaseCanvas();
  74989. this._rightjoystick.releaseCanvas();
  74990. };
  74991. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  74992. return "FreeCameraVirtualJoystickInput";
  74993. };
  74994. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  74995. return "virtualJoystick";
  74996. };
  74997. return FreeCameraVirtualJoystickInput;
  74998. }());
  74999. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  75000. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  75001. })(BABYLON || (BABYLON = {}));
  75002. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  75003. var BABYLON;
  75004. (function (BABYLON) {
  75005. var SimplificationSettings = /** @class */ (function () {
  75006. function SimplificationSettings(quality, distance, optimizeMesh) {
  75007. this.quality = quality;
  75008. this.distance = distance;
  75009. this.optimizeMesh = optimizeMesh;
  75010. }
  75011. return SimplificationSettings;
  75012. }());
  75013. BABYLON.SimplificationSettings = SimplificationSettings;
  75014. var SimplificationQueue = /** @class */ (function () {
  75015. function SimplificationQueue() {
  75016. this.running = false;
  75017. this._simplificationArray = [];
  75018. }
  75019. SimplificationQueue.prototype.addTask = function (task) {
  75020. this._simplificationArray.push(task);
  75021. };
  75022. SimplificationQueue.prototype.executeNext = function () {
  75023. var task = this._simplificationArray.pop();
  75024. if (task) {
  75025. this.running = true;
  75026. this.runSimplification(task);
  75027. }
  75028. else {
  75029. this.running = false;
  75030. }
  75031. };
  75032. SimplificationQueue.prototype.runSimplification = function (task) {
  75033. var _this = this;
  75034. if (task.parallelProcessing) {
  75035. //parallel simplifier
  75036. task.settings.forEach(function (setting) {
  75037. var simplifier = _this.getSimplifier(task);
  75038. simplifier.simplify(setting, function (newMesh) {
  75039. task.mesh.addLODLevel(setting.distance, newMesh);
  75040. newMesh.isVisible = true;
  75041. //check if it is the last
  75042. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  75043. //all done, run the success callback.
  75044. task.successCallback();
  75045. }
  75046. _this.executeNext();
  75047. });
  75048. });
  75049. }
  75050. else {
  75051. //single simplifier.
  75052. var simplifier = this.getSimplifier(task);
  75053. var runDecimation = function (setting, callback) {
  75054. simplifier.simplify(setting, function (newMesh) {
  75055. task.mesh.addLODLevel(setting.distance, newMesh);
  75056. newMesh.isVisible = true;
  75057. //run the next quality level
  75058. callback();
  75059. });
  75060. };
  75061. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  75062. runDecimation(task.settings[loop.index], function () {
  75063. loop.executeNext();
  75064. });
  75065. }, function () {
  75066. //execution ended, run the success callback.
  75067. if (task.successCallback) {
  75068. task.successCallback();
  75069. }
  75070. _this.executeNext();
  75071. });
  75072. }
  75073. };
  75074. SimplificationQueue.prototype.getSimplifier = function (task) {
  75075. switch (task.simplificationType) {
  75076. case SimplificationType.QUADRATIC:
  75077. default:
  75078. return new QuadraticErrorSimplification(task.mesh);
  75079. }
  75080. };
  75081. return SimplificationQueue;
  75082. }());
  75083. BABYLON.SimplificationQueue = SimplificationQueue;
  75084. /**
  75085. * The implemented types of simplification.
  75086. * At the moment only Quadratic Error Decimation is implemented.
  75087. */
  75088. var SimplificationType;
  75089. (function (SimplificationType) {
  75090. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  75091. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  75092. var DecimationTriangle = /** @class */ (function () {
  75093. function DecimationTriangle(vertices) {
  75094. this.vertices = vertices;
  75095. this.error = new Array(4);
  75096. this.deleted = false;
  75097. this.isDirty = false;
  75098. this.deletePending = false;
  75099. this.borderFactor = 0;
  75100. }
  75101. return DecimationTriangle;
  75102. }());
  75103. BABYLON.DecimationTriangle = DecimationTriangle;
  75104. var DecimationVertex = /** @class */ (function () {
  75105. function DecimationVertex(position, id) {
  75106. this.position = position;
  75107. this.id = id;
  75108. this.isBorder = true;
  75109. this.q = new QuadraticMatrix();
  75110. this.triangleCount = 0;
  75111. this.triangleStart = 0;
  75112. this.originalOffsets = [];
  75113. }
  75114. DecimationVertex.prototype.updatePosition = function (newPosition) {
  75115. this.position.copyFrom(newPosition);
  75116. };
  75117. return DecimationVertex;
  75118. }());
  75119. BABYLON.DecimationVertex = DecimationVertex;
  75120. var QuadraticMatrix = /** @class */ (function () {
  75121. function QuadraticMatrix(data) {
  75122. this.data = new Array(10);
  75123. for (var i = 0; i < 10; ++i) {
  75124. if (data && data[i]) {
  75125. this.data[i] = data[i];
  75126. }
  75127. else {
  75128. this.data[i] = 0;
  75129. }
  75130. }
  75131. }
  75132. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  75133. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  75134. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  75135. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  75136. return det;
  75137. };
  75138. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  75139. for (var i = 0; i < 10; ++i) {
  75140. this.data[i] += matrix.data[i];
  75141. }
  75142. };
  75143. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  75144. for (var i = 0; i < 10; ++i) {
  75145. this.data[i] += data[i];
  75146. }
  75147. };
  75148. QuadraticMatrix.prototype.add = function (matrix) {
  75149. var m = new QuadraticMatrix();
  75150. for (var i = 0; i < 10; ++i) {
  75151. m.data[i] = this.data[i] + matrix.data[i];
  75152. }
  75153. return m;
  75154. };
  75155. QuadraticMatrix.FromData = function (a, b, c, d) {
  75156. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  75157. };
  75158. //returning an array to avoid garbage collection
  75159. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  75160. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  75161. };
  75162. return QuadraticMatrix;
  75163. }());
  75164. BABYLON.QuadraticMatrix = QuadraticMatrix;
  75165. var Reference = /** @class */ (function () {
  75166. function Reference(vertexId, triangleId) {
  75167. this.vertexId = vertexId;
  75168. this.triangleId = triangleId;
  75169. }
  75170. return Reference;
  75171. }());
  75172. BABYLON.Reference = Reference;
  75173. /**
  75174. * An implementation of the Quadratic Error simplification algorithm.
  75175. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  75176. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  75177. * @author RaananW
  75178. */
  75179. var QuadraticErrorSimplification = /** @class */ (function () {
  75180. function QuadraticErrorSimplification(_mesh) {
  75181. this._mesh = _mesh;
  75182. this.syncIterations = 5000;
  75183. this.aggressiveness = 7;
  75184. this.decimationIterations = 100;
  75185. this.boundingBoxEpsilon = BABYLON.Epsilon;
  75186. }
  75187. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  75188. var _this = this;
  75189. this.initDecimatedMesh();
  75190. //iterating through the submeshes array, one after the other.
  75191. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  75192. _this.initWithMesh(loop.index, function () {
  75193. _this.runDecimation(settings, loop.index, function () {
  75194. loop.executeNext();
  75195. });
  75196. }, settings.optimizeMesh);
  75197. }, function () {
  75198. setTimeout(function () {
  75199. successCallback(_this._reconstructedMesh);
  75200. }, 0);
  75201. });
  75202. };
  75203. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  75204. var _this = this;
  75205. var targetCount = ~~(this.triangles.length * settings.quality);
  75206. var deletedTriangles = 0;
  75207. var triangleCount = this.triangles.length;
  75208. var iterationFunction = function (iteration, callback) {
  75209. setTimeout(function () {
  75210. if (iteration % 5 === 0) {
  75211. _this.updateMesh(iteration === 0);
  75212. }
  75213. for (var i = 0; i < _this.triangles.length; ++i) {
  75214. _this.triangles[i].isDirty = false;
  75215. }
  75216. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  75217. var trianglesIterator = function (i) {
  75218. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  75219. var t = _this.triangles[tIdx];
  75220. if (!t)
  75221. return;
  75222. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  75223. return;
  75224. }
  75225. for (var j = 0; j < 3; ++j) {
  75226. if (t.error[j] < threshold) {
  75227. var deleted0 = [];
  75228. var deleted1 = [];
  75229. var v0 = t.vertices[j];
  75230. var v1 = t.vertices[(j + 1) % 3];
  75231. if (v0.isBorder || v1.isBorder)
  75232. continue;
  75233. var p = BABYLON.Vector3.Zero();
  75234. var n = BABYLON.Vector3.Zero();
  75235. var uv = BABYLON.Vector2.Zero();
  75236. var color = new BABYLON.Color4(0, 0, 0, 1);
  75237. _this.calculateError(v0, v1, p, n, uv, color);
  75238. var delTr = new Array();
  75239. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  75240. continue;
  75241. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  75242. continue;
  75243. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  75244. continue;
  75245. var uniqueArray = new Array();
  75246. delTr.forEach(function (deletedT) {
  75247. if (uniqueArray.indexOf(deletedT) === -1) {
  75248. deletedT.deletePending = true;
  75249. uniqueArray.push(deletedT);
  75250. }
  75251. });
  75252. if (uniqueArray.length % 2 !== 0) {
  75253. continue;
  75254. }
  75255. v0.q = v1.q.add(v0.q);
  75256. v0.updatePosition(p);
  75257. var tStart = _this.references.length;
  75258. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  75259. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  75260. var tCount = _this.references.length - tStart;
  75261. if (tCount <= v0.triangleCount) {
  75262. if (tCount) {
  75263. for (var c = 0; c < tCount; c++) {
  75264. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  75265. }
  75266. }
  75267. }
  75268. else {
  75269. v0.triangleStart = tStart;
  75270. }
  75271. v0.triangleCount = tCount;
  75272. break;
  75273. }
  75274. }
  75275. };
  75276. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  75277. }, 0);
  75278. };
  75279. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  75280. if (triangleCount - deletedTriangles <= targetCount)
  75281. loop.breakLoop();
  75282. else {
  75283. iterationFunction(loop.index, function () {
  75284. loop.executeNext();
  75285. });
  75286. }
  75287. }, function () {
  75288. setTimeout(function () {
  75289. //reconstruct this part of the mesh
  75290. _this.reconstructMesh(submeshIndex);
  75291. successCallback();
  75292. }, 0);
  75293. });
  75294. };
  75295. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  75296. var _this = this;
  75297. this.vertices = [];
  75298. this.triangles = [];
  75299. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  75300. var indices = this._mesh.getIndices();
  75301. var submesh = this._mesh.subMeshes[submeshIndex];
  75302. var findInVertices = function (positionToSearch) {
  75303. if (optimizeMesh) {
  75304. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  75305. if (_this.vertices[ii].position.equals(positionToSearch)) {
  75306. return _this.vertices[ii];
  75307. }
  75308. }
  75309. }
  75310. return null;
  75311. };
  75312. var vertexReferences = [];
  75313. var vertexInit = function (i) {
  75314. if (!positionData) {
  75315. return;
  75316. }
  75317. var offset = i + submesh.verticesStart;
  75318. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  75319. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  75320. vertex.originalOffsets.push(offset);
  75321. if (vertex.id === _this.vertices.length) {
  75322. _this.vertices.push(vertex);
  75323. }
  75324. vertexReferences.push(vertex.id);
  75325. };
  75326. //var totalVertices = mesh.getTotalVertices();
  75327. var totalVertices = submesh.verticesCount;
  75328. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  75329. var indicesInit = function (i) {
  75330. if (!indices) {
  75331. return;
  75332. }
  75333. var offset = (submesh.indexStart / 3) + i;
  75334. var pos = (offset * 3);
  75335. var i0 = indices[pos + 0];
  75336. var i1 = indices[pos + 1];
  75337. var i2 = indices[pos + 2];
  75338. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  75339. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  75340. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  75341. var triangle = new DecimationTriangle([v0, v1, v2]);
  75342. triangle.originalOffset = pos;
  75343. _this.triangles.push(triangle);
  75344. };
  75345. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  75346. _this.init(callback);
  75347. });
  75348. });
  75349. };
  75350. QuadraticErrorSimplification.prototype.init = function (callback) {
  75351. var _this = this;
  75352. var triangleInit1 = function (i) {
  75353. var t = _this.triangles[i];
  75354. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  75355. for (var j = 0; j < 3; j++) {
  75356. 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))));
  75357. }
  75358. };
  75359. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  75360. var triangleInit2 = function (i) {
  75361. var t = _this.triangles[i];
  75362. for (var j = 0; j < 3; ++j) {
  75363. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  75364. }
  75365. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  75366. };
  75367. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  75368. callback();
  75369. });
  75370. });
  75371. };
  75372. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  75373. var newTriangles = [];
  75374. var i;
  75375. for (i = 0; i < this.vertices.length; ++i) {
  75376. this.vertices[i].triangleCount = 0;
  75377. }
  75378. var t;
  75379. var j;
  75380. for (i = 0; i < this.triangles.length; ++i) {
  75381. if (!this.triangles[i].deleted) {
  75382. t = this.triangles[i];
  75383. for (j = 0; j < 3; ++j) {
  75384. t.vertices[j].triangleCount = 1;
  75385. }
  75386. newTriangles.push(t);
  75387. }
  75388. }
  75389. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  75390. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  75391. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  75392. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  75393. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  75394. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75395. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  75396. var vertexCount = 0;
  75397. for (i = 0; i < this.vertices.length; ++i) {
  75398. var vertex = this.vertices[i];
  75399. vertex.id = vertexCount;
  75400. if (vertex.triangleCount) {
  75401. vertex.originalOffsets.forEach(function (originalOffset) {
  75402. if (!normalData) {
  75403. return;
  75404. }
  75405. newPositionData.push(vertex.position.x);
  75406. newPositionData.push(vertex.position.y);
  75407. newPositionData.push(vertex.position.z);
  75408. newNormalData.push(normalData[originalOffset * 3]);
  75409. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  75410. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  75411. if (uvs && uvs.length) {
  75412. newUVsData.push(uvs[(originalOffset * 2)]);
  75413. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  75414. }
  75415. else if (colorsData && colorsData.length) {
  75416. newColorsData.push(colorsData[(originalOffset * 4)]);
  75417. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  75418. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  75419. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  75420. }
  75421. ++vertexCount;
  75422. });
  75423. }
  75424. }
  75425. var startingIndex = this._reconstructedMesh.getTotalIndices();
  75426. var startingVertex = this._reconstructedMesh.getTotalVertices();
  75427. var submeshesArray = this._reconstructedMesh.subMeshes;
  75428. this._reconstructedMesh.subMeshes = [];
  75429. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  75430. var originalIndices = this._mesh.getIndices();
  75431. for (i = 0; i < newTriangles.length; ++i) {
  75432. t = newTriangles[i]; //now get the new referencing point for each vertex
  75433. [0, 1, 2].forEach(function (idx) {
  75434. var id = originalIndices[t.originalOffset + idx];
  75435. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  75436. if (offset < 0)
  75437. offset = 0;
  75438. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  75439. });
  75440. }
  75441. //overwriting the old vertex buffers and indices.
  75442. this._reconstructedMesh.setIndices(newIndicesArray);
  75443. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  75444. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  75445. if (newUVsData.length > 0)
  75446. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  75447. if (newColorsData.length > 0)
  75448. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  75449. //create submesh
  75450. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  75451. if (submeshIndex > 0) {
  75452. this._reconstructedMesh.subMeshes = [];
  75453. submeshesArray.forEach(function (submesh) {
  75454. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  75455. });
  75456. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  75457. }
  75458. };
  75459. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  75460. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  75461. this._reconstructedMesh.material = this._mesh.material;
  75462. this._reconstructedMesh.parent = this._mesh.parent;
  75463. this._reconstructedMesh.isVisible = false;
  75464. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  75465. };
  75466. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  75467. for (var i = 0; i < vertex1.triangleCount; ++i) {
  75468. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  75469. if (t.deleted)
  75470. continue;
  75471. var s = this.references[vertex1.triangleStart + i].vertexId;
  75472. var v1 = t.vertices[(s + 1) % 3];
  75473. var v2 = t.vertices[(s + 2) % 3];
  75474. if ((v1 === vertex2 || v2 === vertex2)) {
  75475. deletedArray[i] = true;
  75476. delTr.push(t);
  75477. continue;
  75478. }
  75479. var d1 = v1.position.subtract(point);
  75480. d1 = d1.normalize();
  75481. var d2 = v2.position.subtract(point);
  75482. d2 = d2.normalize();
  75483. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  75484. return true;
  75485. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  75486. deletedArray[i] = false;
  75487. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  75488. return true;
  75489. }
  75490. return false;
  75491. };
  75492. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  75493. var newDeleted = deletedTriangles;
  75494. for (var i = 0; i < vertex.triangleCount; ++i) {
  75495. var ref = this.references[vertex.triangleStart + i];
  75496. var t = this.triangles[ref.triangleId];
  75497. if (t.deleted)
  75498. continue;
  75499. if (deletedArray[i] && t.deletePending) {
  75500. t.deleted = true;
  75501. newDeleted++;
  75502. continue;
  75503. }
  75504. t.vertices[ref.vertexId] = origVertex;
  75505. t.isDirty = true;
  75506. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  75507. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  75508. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  75509. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  75510. this.references.push(ref);
  75511. }
  75512. return newDeleted;
  75513. };
  75514. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  75515. for (var i = 0; i < this.vertices.length; ++i) {
  75516. var vCount = [];
  75517. var vId = [];
  75518. var v = this.vertices[i];
  75519. var j;
  75520. for (j = 0; j < v.triangleCount; ++j) {
  75521. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  75522. for (var ii = 0; ii < 3; ii++) {
  75523. var ofs = 0;
  75524. var vv = triangle.vertices[ii];
  75525. while (ofs < vCount.length) {
  75526. if (vId[ofs] === vv.id)
  75527. break;
  75528. ++ofs;
  75529. }
  75530. if (ofs === vCount.length) {
  75531. vCount.push(1);
  75532. vId.push(vv.id);
  75533. }
  75534. else {
  75535. vCount[ofs]++;
  75536. }
  75537. }
  75538. }
  75539. for (j = 0; j < vCount.length; ++j) {
  75540. if (vCount[j] === 1) {
  75541. this.vertices[vId[j]].isBorder = true;
  75542. }
  75543. else {
  75544. this.vertices[vId[j]].isBorder = false;
  75545. }
  75546. }
  75547. }
  75548. };
  75549. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  75550. if (identifyBorders === void 0) { identifyBorders = false; }
  75551. var i;
  75552. if (!identifyBorders) {
  75553. var newTrianglesVector = [];
  75554. for (i = 0; i < this.triangles.length; ++i) {
  75555. if (!this.triangles[i].deleted) {
  75556. newTrianglesVector.push(this.triangles[i]);
  75557. }
  75558. }
  75559. this.triangles = newTrianglesVector;
  75560. }
  75561. for (i = 0; i < this.vertices.length; ++i) {
  75562. this.vertices[i].triangleCount = 0;
  75563. this.vertices[i].triangleStart = 0;
  75564. }
  75565. var t;
  75566. var j;
  75567. var v;
  75568. for (i = 0; i < this.triangles.length; ++i) {
  75569. t = this.triangles[i];
  75570. for (j = 0; j < 3; ++j) {
  75571. v = t.vertices[j];
  75572. v.triangleCount++;
  75573. }
  75574. }
  75575. var tStart = 0;
  75576. for (i = 0; i < this.vertices.length; ++i) {
  75577. this.vertices[i].triangleStart = tStart;
  75578. tStart += this.vertices[i].triangleCount;
  75579. this.vertices[i].triangleCount = 0;
  75580. }
  75581. var newReferences = new Array(this.triangles.length * 3);
  75582. for (i = 0; i < this.triangles.length; ++i) {
  75583. t = this.triangles[i];
  75584. for (j = 0; j < 3; ++j) {
  75585. v = t.vertices[j];
  75586. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  75587. v.triangleCount++;
  75588. }
  75589. }
  75590. this.references = newReferences;
  75591. if (identifyBorders) {
  75592. this.identifyBorder();
  75593. }
  75594. };
  75595. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  75596. var x = point.x;
  75597. var y = point.y;
  75598. var z = point.z;
  75599. 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
  75600. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  75601. };
  75602. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  75603. var q = vertex1.q.add(vertex2.q);
  75604. var border = vertex1.isBorder && vertex2.isBorder;
  75605. var error = 0;
  75606. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  75607. if (qDet !== 0 && !border) {
  75608. if (!pointResult) {
  75609. pointResult = BABYLON.Vector3.Zero();
  75610. }
  75611. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  75612. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  75613. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  75614. error = this.vertexError(q, pointResult);
  75615. }
  75616. else {
  75617. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  75618. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  75619. var error1 = this.vertexError(q, vertex1.position);
  75620. var error2 = this.vertexError(q, vertex2.position);
  75621. var error3 = this.vertexError(q, p3);
  75622. error = Math.min(error1, error2, error3);
  75623. if (error === error1) {
  75624. if (pointResult) {
  75625. pointResult.copyFrom(vertex1.position);
  75626. }
  75627. }
  75628. else if (error === error2) {
  75629. if (pointResult) {
  75630. pointResult.copyFrom(vertex2.position);
  75631. }
  75632. }
  75633. else {
  75634. if (pointResult) {
  75635. pointResult.copyFrom(p3);
  75636. }
  75637. }
  75638. }
  75639. return error;
  75640. };
  75641. return QuadraticErrorSimplification;
  75642. }());
  75643. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  75644. })(BABYLON || (BABYLON = {}));
  75645. //# sourceMappingURL=babylon.meshSimplification.js.map
  75646. var BABYLON;
  75647. (function (BABYLON) {
  75648. var MeshLODLevel = /** @class */ (function () {
  75649. function MeshLODLevel(distance, mesh) {
  75650. this.distance = distance;
  75651. this.mesh = mesh;
  75652. }
  75653. return MeshLODLevel;
  75654. }());
  75655. BABYLON.MeshLODLevel = MeshLODLevel;
  75656. })(BABYLON || (BABYLON = {}));
  75657. //# sourceMappingURL=babylon.meshLODLevel.js.map
  75658. var BABYLON;
  75659. (function (BABYLON) {
  75660. /**
  75661. * Defines the root class used to create scene optimization to use with SceneOptimizer
  75662. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75663. */
  75664. var SceneOptimization = /** @class */ (function () {
  75665. /**
  75666. * Creates the SceneOptimization object
  75667. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75668. * @param desc defines the description associated with the optimization
  75669. */
  75670. function SceneOptimization(priority) {
  75671. if (priority === void 0) { priority = 0; }
  75672. this.priority = priority;
  75673. }
  75674. /**
  75675. * Gets a string describing the action executed by the current optimization
  75676. */
  75677. SceneOptimization.prototype.getDescription = function () {
  75678. return "";
  75679. };
  75680. /**
  75681. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75682. * @param scene defines the current scene where to apply this optimization
  75683. * @returnstrue if everything that can be done was applied
  75684. */
  75685. SceneOptimization.prototype.apply = function (scene) {
  75686. return true;
  75687. };
  75688. ;
  75689. return SceneOptimization;
  75690. }());
  75691. BABYLON.SceneOptimization = SceneOptimization;
  75692. /**
  75693. * Defines an optimization used to reduce the size of render target textures
  75694. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75695. */
  75696. var TextureOptimization = /** @class */ (function (_super) {
  75697. __extends(TextureOptimization, _super);
  75698. /**
  75699. * Creates the TextureOptimization object
  75700. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75701. * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  75702. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  75703. */
  75704. function TextureOptimization(priority, maximumSize, step) {
  75705. if (priority === void 0) { priority = 0; }
  75706. if (maximumSize === void 0) { maximumSize = 1024; }
  75707. if (step === void 0) { step = 0.5; }
  75708. var _this = _super.call(this, priority) || this;
  75709. _this.priority = priority;
  75710. _this.maximumSize = maximumSize;
  75711. _this.step = step;
  75712. return _this;
  75713. }
  75714. /**
  75715. * Gets a string describing the action executed by the current optimization
  75716. */
  75717. TextureOptimization.prototype.getDescription = function () {
  75718. return "Reducing render target texture size to " + this.maximumSize;
  75719. };
  75720. /**
  75721. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75722. * @param scene defines the current scene where to apply this optimization
  75723. */
  75724. TextureOptimization.prototype.apply = function (scene) {
  75725. var allDone = true;
  75726. for (var index = 0; index < scene.textures.length; index++) {
  75727. var texture = scene.textures[index];
  75728. if (!texture.canRescale || texture.getContext) {
  75729. continue;
  75730. }
  75731. var currentSize = texture.getSize();
  75732. var maxDimension = Math.max(currentSize.width, currentSize.height);
  75733. if (maxDimension > this.maximumSize) {
  75734. texture.scale(this.step);
  75735. allDone = false;
  75736. }
  75737. }
  75738. return allDone;
  75739. };
  75740. return TextureOptimization;
  75741. }(SceneOptimization));
  75742. BABYLON.TextureOptimization = TextureOptimization;
  75743. /**
  75744. * Defines an optimization used to increase or decrease the rendering resolution
  75745. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75746. */
  75747. var HardwareScalingOptimization = /** @class */ (function (_super) {
  75748. __extends(HardwareScalingOptimization, _super);
  75749. /**
  75750. * Creates the HardwareScalingOptimization object
  75751. * @param priority priority defines the priority of this optimization (0 by default which means first in the list)
  75752. * @param maximumScale
  75753. * @param step
  75754. */
  75755. function HardwareScalingOptimization(priority, maximumScale, step) {
  75756. if (priority === void 0) { priority = 0; }
  75757. if (maximumScale === void 0) { maximumScale = 2; }
  75758. if (step === void 0) { step = 0.25; }
  75759. var _this = _super.call(this, priority) || this;
  75760. _this.priority = priority;
  75761. _this.maximumScale = maximumScale;
  75762. _this.step = step;
  75763. _this._currentScale = -1;
  75764. _this._directionOffset = 1;
  75765. return _this;
  75766. }
  75767. /**
  75768. * Gets a string describing the action executed by the current optimization
  75769. */
  75770. HardwareScalingOptimization.prototype.getDescription = function () {
  75771. return "Setting hardware scaling level to " + this._currentScale;
  75772. };
  75773. /**
  75774. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75775. * @param scene defines the current scene where to apply this optimization
  75776. */
  75777. HardwareScalingOptimization.prototype.apply = function (scene) {
  75778. if (this._currentScale === -1) {
  75779. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  75780. if (this._currentScale > this.maximumScale) {
  75781. this._directionOffset = -1;
  75782. }
  75783. }
  75784. this._currentScale += this._directionOffset * this.step;
  75785. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  75786. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  75787. };
  75788. ;
  75789. return HardwareScalingOptimization;
  75790. }(SceneOptimization));
  75791. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  75792. /**
  75793. * Defines an optimization used to remove shadows
  75794. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75795. */
  75796. var ShadowsOptimization = /** @class */ (function (_super) {
  75797. __extends(ShadowsOptimization, _super);
  75798. function ShadowsOptimization() {
  75799. return _super !== null && _super.apply(this, arguments) || this;
  75800. }
  75801. /**
  75802. * Gets a string describing the action executed by the current optimization
  75803. */
  75804. ShadowsOptimization.prototype.getDescription = function () {
  75805. return "Turning shadows off";
  75806. };
  75807. /**
  75808. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75809. * @param scene defines the current scene where to apply this optimization
  75810. */
  75811. ShadowsOptimization.prototype.apply = function (scene) {
  75812. scene.shadowsEnabled = false;
  75813. return true;
  75814. };
  75815. ;
  75816. return ShadowsOptimization;
  75817. }(SceneOptimization));
  75818. BABYLON.ShadowsOptimization = ShadowsOptimization;
  75819. /**
  75820. * Defines an optimization used to turn post-processes off
  75821. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75822. */
  75823. var PostProcessesOptimization = /** @class */ (function (_super) {
  75824. __extends(PostProcessesOptimization, _super);
  75825. function PostProcessesOptimization() {
  75826. return _super !== null && _super.apply(this, arguments) || this;
  75827. }
  75828. /**
  75829. * Gets a string describing the action executed by the current optimization
  75830. */
  75831. PostProcessesOptimization.prototype.getDescription = function () {
  75832. return "Turning post-processes off";
  75833. };
  75834. /**
  75835. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75836. * @param scene defines the current scene where to apply this optimization
  75837. */
  75838. PostProcessesOptimization.prototype.apply = function (scene) {
  75839. scene.postProcessesEnabled = false;
  75840. return true;
  75841. };
  75842. ;
  75843. return PostProcessesOptimization;
  75844. }(SceneOptimization));
  75845. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  75846. /**
  75847. * Defines an optimization used to turn lens flares off
  75848. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75849. */
  75850. var LensFlaresOptimization = /** @class */ (function (_super) {
  75851. __extends(LensFlaresOptimization, _super);
  75852. function LensFlaresOptimization() {
  75853. return _super !== null && _super.apply(this, arguments) || this;
  75854. }
  75855. /**
  75856. * Gets a string describing the action executed by the current optimization
  75857. */
  75858. LensFlaresOptimization.prototype.getDescription = function () {
  75859. return "Turning lens flares off";
  75860. };
  75861. /**
  75862. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75863. * @param scene defines the current scene where to apply this optimization
  75864. */
  75865. LensFlaresOptimization.prototype.apply = function (scene) {
  75866. scene.lensFlaresEnabled = false;
  75867. return true;
  75868. };
  75869. ;
  75870. return LensFlaresOptimization;
  75871. }(SceneOptimization));
  75872. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  75873. /**
  75874. * Defines an optimization based on user defined callback.
  75875. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75876. */
  75877. var CustomOptimization = /** @class */ (function (_super) {
  75878. __extends(CustomOptimization, _super);
  75879. function CustomOptimization() {
  75880. return _super !== null && _super.apply(this, arguments) || this;
  75881. }
  75882. /**
  75883. * Gets a string describing the action executed by the current optimization
  75884. */
  75885. CustomOptimization.prototype.getDescription = function () {
  75886. if (this.onGetDescription) {
  75887. return this.onGetDescription();
  75888. }
  75889. return "Running user defined callback";
  75890. };
  75891. /**
  75892. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75893. * @param scene defines the current scene where to apply this optimization
  75894. */
  75895. CustomOptimization.prototype.apply = function (scene) {
  75896. if (this.onApply) {
  75897. return this.onApply(scene);
  75898. }
  75899. return true;
  75900. };
  75901. ;
  75902. return CustomOptimization;
  75903. }(SceneOptimization));
  75904. BABYLON.CustomOptimization = CustomOptimization;
  75905. /**
  75906. * Defines an optimization used to turn particles off
  75907. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75908. */
  75909. var ParticlesOptimization = /** @class */ (function (_super) {
  75910. __extends(ParticlesOptimization, _super);
  75911. function ParticlesOptimization() {
  75912. return _super !== null && _super.apply(this, arguments) || this;
  75913. }
  75914. /**
  75915. * Gets a string describing the action executed by the current optimization
  75916. */
  75917. ParticlesOptimization.prototype.getDescription = function () {
  75918. return "Turning particles off";
  75919. };
  75920. /**
  75921. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75922. * @param scene defines the current scene where to apply this optimization
  75923. */
  75924. ParticlesOptimization.prototype.apply = function (scene) {
  75925. scene.particlesEnabled = false;
  75926. return true;
  75927. };
  75928. ;
  75929. return ParticlesOptimization;
  75930. }(SceneOptimization));
  75931. BABYLON.ParticlesOptimization = ParticlesOptimization;
  75932. /**
  75933. * Defines an optimization used to turn render targets off
  75934. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75935. */
  75936. var RenderTargetsOptimization = /** @class */ (function (_super) {
  75937. __extends(RenderTargetsOptimization, _super);
  75938. function RenderTargetsOptimization() {
  75939. return _super !== null && _super.apply(this, arguments) || this;
  75940. }
  75941. /**
  75942. * Gets a string describing the action executed by the current optimization
  75943. */
  75944. RenderTargetsOptimization.prototype.getDescription = function () {
  75945. return "Turning render targets off";
  75946. };
  75947. /**
  75948. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75949. * @param scene defines the current scene where to apply this optimization
  75950. */
  75951. RenderTargetsOptimization.prototype.apply = function (scene) {
  75952. scene.renderTargetsEnabled = false;
  75953. return true;
  75954. };
  75955. ;
  75956. return RenderTargetsOptimization;
  75957. }(SceneOptimization));
  75958. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  75959. /**
  75960. * Defines an optimization used to merge meshes with compatible materials
  75961. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75962. */
  75963. var MergeMeshesOptimization = /** @class */ (function (_super) {
  75964. __extends(MergeMeshesOptimization, _super);
  75965. function MergeMeshesOptimization() {
  75966. var _this = _super !== null && _super.apply(this, arguments) || this;
  75967. _this._canBeMerged = function (abstractMesh) {
  75968. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  75969. return false;
  75970. }
  75971. var mesh = abstractMesh;
  75972. if (!mesh.isVisible || !mesh.isEnabled()) {
  75973. return false;
  75974. }
  75975. if (mesh.instances.length > 0) {
  75976. return false;
  75977. }
  75978. if (mesh.skeleton || mesh.hasLODLevels) {
  75979. return false;
  75980. }
  75981. if (mesh.parent) {
  75982. return false;
  75983. }
  75984. return true;
  75985. };
  75986. return _this;
  75987. }
  75988. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  75989. /**
  75990. * Gets or sets a boolean which defines if optimization octree has to be updated
  75991. */
  75992. get: function () {
  75993. return MergeMeshesOptimization._UpdateSelectionTree;
  75994. },
  75995. /**
  75996. * Gets or sets a boolean which defines if optimization octree has to be updated
  75997. */
  75998. set: function (value) {
  75999. MergeMeshesOptimization._UpdateSelectionTree = value;
  76000. },
  76001. enumerable: true,
  76002. configurable: true
  76003. });
  76004. /**
  76005. * Gets a string describing the action executed by the current optimization
  76006. */
  76007. MergeMeshesOptimization.prototype.getDescription = function () {
  76008. return "Merging similar meshes together";
  76009. };
  76010. /**
  76011. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  76012. * @param scene defines the current scene where to apply this optimization
  76013. */
  76014. MergeMeshesOptimization.prototype.apply = function (scene, updateSelectionTree) {
  76015. var globalPool = scene.meshes.slice(0);
  76016. var globalLength = globalPool.length;
  76017. for (var index = 0; index < globalLength; index++) {
  76018. var currentPool = new Array();
  76019. var current = globalPool[index];
  76020. // Checks
  76021. if (!this._canBeMerged(current)) {
  76022. continue;
  76023. }
  76024. currentPool.push(current);
  76025. // Find compatible meshes
  76026. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  76027. var otherMesh = globalPool[subIndex];
  76028. if (!this._canBeMerged(otherMesh)) {
  76029. continue;
  76030. }
  76031. if (otherMesh.material !== current.material) {
  76032. continue;
  76033. }
  76034. if (otherMesh.checkCollisions !== current.checkCollisions) {
  76035. continue;
  76036. }
  76037. currentPool.push(otherMesh);
  76038. globalLength--;
  76039. globalPool.splice(subIndex, 1);
  76040. subIndex--;
  76041. }
  76042. if (currentPool.length < 2) {
  76043. continue;
  76044. }
  76045. // Merge meshes
  76046. BABYLON.Mesh.MergeMeshes(currentPool);
  76047. }
  76048. if (updateSelectionTree != undefined) {
  76049. if (updateSelectionTree) {
  76050. scene.createOrUpdateSelectionOctree();
  76051. }
  76052. }
  76053. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  76054. scene.createOrUpdateSelectionOctree();
  76055. }
  76056. return true;
  76057. };
  76058. ;
  76059. MergeMeshesOptimization._UpdateSelectionTree = false;
  76060. return MergeMeshesOptimization;
  76061. }(SceneOptimization));
  76062. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  76063. /**
  76064. * Defines a list of options used by SceneOptimizer
  76065. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  76066. */
  76067. var SceneOptimizerOptions = /** @class */ (function () {
  76068. /**
  76069. * Creates a new list of options used by SceneOptimizer
  76070. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  76071. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  76072. */
  76073. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  76074. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  76075. if (trackerDuration === void 0) { trackerDuration = 2000; }
  76076. this.targetFrameRate = targetFrameRate;
  76077. this.trackerDuration = trackerDuration;
  76078. /**
  76079. * Gets the list of optimizations to apply
  76080. */
  76081. this.optimizations = new Array();
  76082. }
  76083. /**
  76084. * Add a new optimization
  76085. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  76086. */
  76087. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  76088. this.optimizations.push(optimization);
  76089. return this;
  76090. };
  76091. /**
  76092. * Add a new custom optimization
  76093. * @param onApply defines the callback called to apply the custom optimization.
  76094. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  76095. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  76096. */
  76097. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  76098. if (priority === void 0) { priority = 0; }
  76099. var optimization = new CustomOptimization(priority);
  76100. optimization.onApply = onApply;
  76101. optimization.onGetDescription = onGetDescription;
  76102. this.optimizations.push(optimization);
  76103. return this;
  76104. };
  76105. /**
  76106. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  76107. * @param targetFrameRate defines the target frame rate (60 by default)
  76108. * @returns a SceneOptimizerOptions object
  76109. */
  76110. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  76111. var result = new SceneOptimizerOptions(targetFrameRate);
  76112. var priority = 0;
  76113. result.addOptimization(new MergeMeshesOptimization(priority));
  76114. result.addOptimization(new ShadowsOptimization(priority));
  76115. result.addOptimization(new LensFlaresOptimization(priority));
  76116. // Next priority
  76117. priority++;
  76118. result.addOptimization(new PostProcessesOptimization(priority));
  76119. result.addOptimization(new ParticlesOptimization(priority));
  76120. // Next priority
  76121. priority++;
  76122. result.addOptimization(new TextureOptimization(priority, 1024));
  76123. return result;
  76124. };
  76125. /**
  76126. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  76127. * @param targetFrameRate defines the target frame rate (60 by default)
  76128. * @returns a SceneOptimizerOptions object
  76129. */
  76130. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  76131. var result = new SceneOptimizerOptions(targetFrameRate);
  76132. var priority = 0;
  76133. result.addOptimization(new MergeMeshesOptimization(priority));
  76134. result.addOptimization(new ShadowsOptimization(priority));
  76135. result.addOptimization(new LensFlaresOptimization(priority));
  76136. // Next priority
  76137. priority++;
  76138. result.addOptimization(new PostProcessesOptimization(priority));
  76139. result.addOptimization(new ParticlesOptimization(priority));
  76140. // Next priority
  76141. priority++;
  76142. result.addOptimization(new TextureOptimization(priority, 512));
  76143. // Next priority
  76144. priority++;
  76145. result.addOptimization(new RenderTargetsOptimization(priority));
  76146. // Next priority
  76147. priority++;
  76148. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  76149. return result;
  76150. };
  76151. /**
  76152. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  76153. * @param targetFrameRate defines the target frame rate (60 by default)
  76154. * @returns a SceneOptimizerOptions object
  76155. */
  76156. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  76157. var result = new SceneOptimizerOptions(targetFrameRate);
  76158. var priority = 0;
  76159. result.addOptimization(new MergeMeshesOptimization(priority));
  76160. result.addOptimization(new ShadowsOptimization(priority));
  76161. result.addOptimization(new LensFlaresOptimization(priority));
  76162. // Next priority
  76163. priority++;
  76164. result.addOptimization(new PostProcessesOptimization(priority));
  76165. result.addOptimization(new ParticlesOptimization(priority));
  76166. // Next priority
  76167. priority++;
  76168. result.addOptimization(new TextureOptimization(priority, 256));
  76169. // Next priority
  76170. priority++;
  76171. result.addOptimization(new RenderTargetsOptimization(priority));
  76172. // Next priority
  76173. priority++;
  76174. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  76175. return result;
  76176. };
  76177. return SceneOptimizerOptions;
  76178. }());
  76179. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  76180. /**
  76181. * Class used to run optimizations in order to reach a target frame rate
  76182. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  76183. */
  76184. var SceneOptimizer = /** @class */ (function () {
  76185. /**
  76186. * Creates a new SceneOptimizer
  76187. * @param scene defines the scene to work on
  76188. * @param options defines the options to use with the SceneOptimizer
  76189. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  76190. */
  76191. function SceneOptimizer(scene, options, autoGeneratePriorities) {
  76192. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  76193. var _this = this;
  76194. this._isRunning = false;
  76195. this._currentPriorityLevel = 0;
  76196. this._targetFrameRate = 60;
  76197. this._trackerDuration = 2000;
  76198. this._currentFrameRate = 0;
  76199. /**
  76200. * Defines an observable called when the optimizer reaches the target frame rate
  76201. */
  76202. this.onSuccessObservable = new BABYLON.Observable();
  76203. /**
  76204. * Defines an observable called when the optimizer enables an optimization
  76205. */
  76206. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  76207. /**
  76208. * Defines an observable called when the optimizer is not able to reach the target frame rate
  76209. */
  76210. this.onFailureObservable = new BABYLON.Observable();
  76211. if (!options) {
  76212. this._options = new SceneOptimizerOptions();
  76213. }
  76214. else {
  76215. this._options = options;
  76216. }
  76217. if (this._options.targetFrameRate) {
  76218. this._targetFrameRate = this._options.targetFrameRate;
  76219. }
  76220. if (this._options.trackerDuration) {
  76221. this._trackerDuration = this._options.trackerDuration;
  76222. }
  76223. if (autoGeneratePriorities) {
  76224. var priority = 0;
  76225. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  76226. var optim = _a[_i];
  76227. optim.priority = priority++;
  76228. }
  76229. }
  76230. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76231. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  76232. _this._sceneDisposeObserver = null;
  76233. _this.dispose();
  76234. });
  76235. }
  76236. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  76237. /**
  76238. * Gets the current priority level (0 at start)
  76239. */
  76240. get: function () {
  76241. return this._currentPriorityLevel;
  76242. },
  76243. enumerable: true,
  76244. configurable: true
  76245. });
  76246. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  76247. /**
  76248. * Gets the current frame rate checked by the SceneOptimizer
  76249. */
  76250. get: function () {
  76251. return this._currentFrameRate;
  76252. },
  76253. enumerable: true,
  76254. configurable: true
  76255. });
  76256. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  76257. /**
  76258. * Gets or sets the current target frame rate (60 by default)
  76259. */
  76260. get: function () {
  76261. return this._targetFrameRate;
  76262. },
  76263. /**
  76264. * Gets or sets the current target frame rate (60 by default)
  76265. */
  76266. set: function (value) {
  76267. this._targetFrameRate = value;
  76268. },
  76269. enumerable: true,
  76270. configurable: true
  76271. });
  76272. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  76273. /**
  76274. * Gets or sets the current interval between two checks (every 2000ms by default)
  76275. */
  76276. get: function () {
  76277. return this._trackerDuration;
  76278. },
  76279. /**
  76280. * Gets or sets the current interval between two checks (every 2000ms by default)
  76281. */
  76282. set: function (value) {
  76283. this._trackerDuration = value;
  76284. },
  76285. enumerable: true,
  76286. configurable: true
  76287. });
  76288. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  76289. /**
  76290. * Gets the list of active optimizations
  76291. */
  76292. get: function () {
  76293. return this._options.optimizations;
  76294. },
  76295. enumerable: true,
  76296. configurable: true
  76297. });
  76298. /**
  76299. * Stops the current optimizer
  76300. */
  76301. SceneOptimizer.prototype.stop = function () {
  76302. this._isRunning = false;
  76303. };
  76304. SceneOptimizer.prototype.reset = function () {
  76305. this._currentPriorityLevel = 0;
  76306. };
  76307. SceneOptimizer.prototype.start = function () {
  76308. var _this = this;
  76309. if (this._isRunning) {
  76310. return;
  76311. }
  76312. this._isRunning = true;
  76313. // Let's wait for the scene to be ready before running our check
  76314. this._scene.executeWhenReady(function () {
  76315. setTimeout(function () {
  76316. _this._checkCurrentState();
  76317. }, _this._trackerDuration);
  76318. });
  76319. };
  76320. SceneOptimizer.prototype._checkCurrentState = function () {
  76321. var _this = this;
  76322. if (!this._isRunning) {
  76323. return;
  76324. }
  76325. var scene = this._scene;
  76326. var options = this._options;
  76327. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  76328. if (this._currentFrameRate >= this._targetFrameRate) {
  76329. this._isRunning = false;
  76330. this.onSuccessObservable.notifyObservers(this);
  76331. return;
  76332. }
  76333. // Apply current level of optimizations
  76334. var allDone = true;
  76335. var noOptimizationApplied = true;
  76336. for (var index = 0; index < options.optimizations.length; index++) {
  76337. var optimization = options.optimizations[index];
  76338. if (optimization.priority === this._currentPriorityLevel) {
  76339. noOptimizationApplied = false;
  76340. allDone = allDone && optimization.apply(scene);
  76341. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  76342. }
  76343. }
  76344. // If no optimization was applied, this is a failure :(
  76345. if (noOptimizationApplied) {
  76346. this._isRunning = false;
  76347. this.onFailureObservable.notifyObservers(this);
  76348. return;
  76349. }
  76350. // If all optimizations were done, move to next level
  76351. if (allDone) {
  76352. this._currentPriorityLevel++;
  76353. }
  76354. // Let's the system running for a specific amount of time before checking FPS
  76355. scene.executeWhenReady(function () {
  76356. setTimeout(function () {
  76357. _this._checkCurrentState();
  76358. }, _this._trackerDuration);
  76359. });
  76360. };
  76361. /**
  76362. * Release all resources
  76363. */
  76364. SceneOptimizer.prototype.dispose = function () {
  76365. this.stop();
  76366. this.onSuccessObservable.clear();
  76367. this.onFailureObservable.clear();
  76368. this.onNewOptimizationAppliedObservable.clear();
  76369. if (this._sceneDisposeObserver) {
  76370. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  76371. }
  76372. };
  76373. /**
  76374. * Helper function to create a SceneOptimizer with one single line of code
  76375. * @param scene defines the scene to work on
  76376. * @param options defines the options to use with the SceneOptimizer
  76377. * @param onSuccess defines a callback to call on success
  76378. * @param onFailure defines a callback to call on failure
  76379. */
  76380. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  76381. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  76382. if (onSuccess) {
  76383. optimizer.onSuccessObservable.add(function () {
  76384. onSuccess();
  76385. });
  76386. }
  76387. if (onFailure) {
  76388. optimizer.onFailureObservable.add(function () {
  76389. onFailure();
  76390. });
  76391. }
  76392. optimizer.start();
  76393. return optimizer;
  76394. };
  76395. return SceneOptimizer;
  76396. }());
  76397. BABYLON.SceneOptimizer = SceneOptimizer;
  76398. })(BABYLON || (BABYLON = {}));
  76399. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  76400. var BABYLON;
  76401. (function (BABYLON) {
  76402. var OutlineRenderer = /** @class */ (function () {
  76403. function OutlineRenderer(scene) {
  76404. this.zOffset = 1;
  76405. this._scene = scene;
  76406. }
  76407. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  76408. var _this = this;
  76409. if (useOverlay === void 0) { useOverlay = false; }
  76410. var scene = this._scene;
  76411. var engine = this._scene.getEngine();
  76412. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76413. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  76414. return;
  76415. }
  76416. var mesh = subMesh.getRenderingMesh();
  76417. var material = subMesh.getMaterial();
  76418. if (!material || !scene.activeCamera) {
  76419. return;
  76420. }
  76421. engine.enableEffect(this._effect);
  76422. // Logarithmic depth
  76423. if (material.useLogarithmicDepth) {
  76424. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  76425. }
  76426. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  76427. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  76428. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76429. // Bones
  76430. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76431. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76432. }
  76433. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  76434. // Alpha test
  76435. if (material && material.needAlphaTesting()) {
  76436. var alphaTexture = material.getAlphaTestTexture();
  76437. if (alphaTexture) {
  76438. this._effect.setTexture("diffuseSampler", alphaTexture);
  76439. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76440. }
  76441. }
  76442. engine.setZOffset(-this.zOffset);
  76443. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  76444. engine.setZOffset(0);
  76445. };
  76446. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  76447. var defines = [];
  76448. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76449. var mesh = subMesh.getMesh();
  76450. var material = subMesh.getMaterial();
  76451. if (material) {
  76452. // Alpha test
  76453. if (material.needAlphaTesting()) {
  76454. defines.push("#define ALPHATEST");
  76455. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76456. attribs.push(BABYLON.VertexBuffer.UVKind);
  76457. defines.push("#define UV1");
  76458. }
  76459. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76460. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76461. defines.push("#define UV2");
  76462. }
  76463. }
  76464. //Logarithmic depth
  76465. if (material.useLogarithmicDepth) {
  76466. defines.push("#define LOGARITHMICDEPTH");
  76467. }
  76468. }
  76469. // Bones
  76470. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76471. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76472. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76473. if (mesh.numBoneInfluencers > 4) {
  76474. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76475. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76476. }
  76477. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76478. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76479. }
  76480. else {
  76481. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76482. }
  76483. // Instances
  76484. if (useInstances) {
  76485. defines.push("#define INSTANCES");
  76486. attribs.push("world0");
  76487. attribs.push("world1");
  76488. attribs.push("world2");
  76489. attribs.push("world3");
  76490. }
  76491. // Get correct effect
  76492. var join = defines.join("\n");
  76493. if (this._cachedDefines !== join) {
  76494. this._cachedDefines = join;
  76495. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  76496. }
  76497. return this._effect.isReady();
  76498. };
  76499. return OutlineRenderer;
  76500. }());
  76501. BABYLON.OutlineRenderer = OutlineRenderer;
  76502. })(BABYLON || (BABYLON = {}));
  76503. //# sourceMappingURL=babylon.outlineRenderer.js.map
  76504. var BABYLON;
  76505. (function (BABYLON) {
  76506. var FaceAdjacencies = /** @class */ (function () {
  76507. function FaceAdjacencies() {
  76508. this.edges = new Array();
  76509. this.edgesConnectedCount = 0;
  76510. }
  76511. return FaceAdjacencies;
  76512. }());
  76513. var EdgesRenderer = /** @class */ (function () {
  76514. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  76515. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  76516. if (epsilon === void 0) { epsilon = 0.95; }
  76517. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  76518. this.edgesWidthScalerForOrthographic = 1000.0;
  76519. this.edgesWidthScalerForPerspective = 50.0;
  76520. this._linesPositions = new Array();
  76521. this._linesNormals = new Array();
  76522. this._linesIndices = new Array();
  76523. this._buffers = {};
  76524. this._checkVerticesInsteadOfIndices = false;
  76525. this._source = source;
  76526. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  76527. this._epsilon = epsilon;
  76528. this._prepareRessources();
  76529. this._generateEdgesLines();
  76530. }
  76531. EdgesRenderer.prototype._prepareRessources = function () {
  76532. if (this._lineShader) {
  76533. return;
  76534. }
  76535. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  76536. attributes: ["position", "normal"],
  76537. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  76538. });
  76539. this._lineShader.disableDepthWrite = true;
  76540. this._lineShader.backFaceCulling = false;
  76541. };
  76542. EdgesRenderer.prototype._rebuild = function () {
  76543. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  76544. if (buffer) {
  76545. buffer._rebuild();
  76546. }
  76547. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  76548. if (buffer) {
  76549. buffer._rebuild();
  76550. }
  76551. var scene = this._source.getScene();
  76552. var engine = scene.getEngine();
  76553. this._ib = engine.createIndexBuffer(this._linesIndices);
  76554. };
  76555. EdgesRenderer.prototype.dispose = function () {
  76556. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  76557. if (buffer) {
  76558. buffer.dispose();
  76559. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  76560. }
  76561. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  76562. if (buffer) {
  76563. buffer.dispose();
  76564. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  76565. }
  76566. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  76567. this._lineShader.dispose();
  76568. };
  76569. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  76570. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  76571. return 0;
  76572. }
  76573. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  76574. return 1;
  76575. }
  76576. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  76577. return 2;
  76578. }
  76579. return -1;
  76580. };
  76581. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  76582. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  76583. return 0;
  76584. }
  76585. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  76586. return 1;
  76587. }
  76588. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  76589. return 2;
  76590. }
  76591. return -1;
  76592. };
  76593. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  76594. var needToCreateLine;
  76595. if (edge === undefined) {
  76596. needToCreateLine = true;
  76597. }
  76598. else {
  76599. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  76600. needToCreateLine = dotProduct < this._epsilon;
  76601. }
  76602. if (needToCreateLine) {
  76603. var offset = this._linesPositions.length / 3;
  76604. var normal = p0.subtract(p1);
  76605. normal.normalize();
  76606. // Positions
  76607. this._linesPositions.push(p0.x);
  76608. this._linesPositions.push(p0.y);
  76609. this._linesPositions.push(p0.z);
  76610. this._linesPositions.push(p0.x);
  76611. this._linesPositions.push(p0.y);
  76612. this._linesPositions.push(p0.z);
  76613. this._linesPositions.push(p1.x);
  76614. this._linesPositions.push(p1.y);
  76615. this._linesPositions.push(p1.z);
  76616. this._linesPositions.push(p1.x);
  76617. this._linesPositions.push(p1.y);
  76618. this._linesPositions.push(p1.z);
  76619. // Normals
  76620. this._linesNormals.push(p1.x);
  76621. this._linesNormals.push(p1.y);
  76622. this._linesNormals.push(p1.z);
  76623. this._linesNormals.push(-1);
  76624. this._linesNormals.push(p1.x);
  76625. this._linesNormals.push(p1.y);
  76626. this._linesNormals.push(p1.z);
  76627. this._linesNormals.push(1);
  76628. this._linesNormals.push(p0.x);
  76629. this._linesNormals.push(p0.y);
  76630. this._linesNormals.push(p0.z);
  76631. this._linesNormals.push(-1);
  76632. this._linesNormals.push(p0.x);
  76633. this._linesNormals.push(p0.y);
  76634. this._linesNormals.push(p0.z);
  76635. this._linesNormals.push(1);
  76636. // Indices
  76637. this._linesIndices.push(offset);
  76638. this._linesIndices.push(offset + 1);
  76639. this._linesIndices.push(offset + 2);
  76640. this._linesIndices.push(offset);
  76641. this._linesIndices.push(offset + 2);
  76642. this._linesIndices.push(offset + 3);
  76643. }
  76644. };
  76645. EdgesRenderer.prototype._generateEdgesLines = function () {
  76646. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  76647. var indices = this._source.getIndices();
  76648. if (!indices || !positions) {
  76649. return;
  76650. }
  76651. // First let's find adjacencies
  76652. var adjacencies = new Array();
  76653. var faceNormals = new Array();
  76654. var index;
  76655. var faceAdjacencies;
  76656. // Prepare faces
  76657. for (index = 0; index < indices.length; index += 3) {
  76658. faceAdjacencies = new FaceAdjacencies();
  76659. var p0Index = indices[index];
  76660. var p1Index = indices[index + 1];
  76661. var p2Index = indices[index + 2];
  76662. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  76663. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  76664. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  76665. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  76666. faceNormal.normalize();
  76667. faceNormals.push(faceNormal);
  76668. adjacencies.push(faceAdjacencies);
  76669. }
  76670. // Scan
  76671. for (index = 0; index < adjacencies.length; index++) {
  76672. faceAdjacencies = adjacencies[index];
  76673. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  76674. var otherFaceAdjacencies = adjacencies[otherIndex];
  76675. if (faceAdjacencies.edgesConnectedCount === 3) {
  76676. break;
  76677. }
  76678. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  76679. continue;
  76680. }
  76681. var otherP0 = indices[otherIndex * 3];
  76682. var otherP1 = indices[otherIndex * 3 + 1];
  76683. var otherP2 = indices[otherIndex * 3 + 2];
  76684. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  76685. var otherEdgeIndex = 0;
  76686. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  76687. continue;
  76688. }
  76689. switch (edgeIndex) {
  76690. case 0:
  76691. if (this._checkVerticesInsteadOfIndices) {
  76692. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76693. }
  76694. else {
  76695. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  76696. }
  76697. break;
  76698. case 1:
  76699. if (this._checkVerticesInsteadOfIndices) {
  76700. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76701. }
  76702. else {
  76703. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  76704. }
  76705. break;
  76706. case 2:
  76707. if (this._checkVerticesInsteadOfIndices) {
  76708. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76709. }
  76710. else {
  76711. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  76712. }
  76713. break;
  76714. }
  76715. if (otherEdgeIndex === -1) {
  76716. continue;
  76717. }
  76718. faceAdjacencies.edges[edgeIndex] = otherIndex;
  76719. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  76720. faceAdjacencies.edgesConnectedCount++;
  76721. otherFaceAdjacencies.edgesConnectedCount++;
  76722. if (faceAdjacencies.edgesConnectedCount === 3) {
  76723. break;
  76724. }
  76725. }
  76726. }
  76727. }
  76728. // Create lines
  76729. for (index = 0; index < adjacencies.length; index++) {
  76730. // 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
  76731. var current = adjacencies[index];
  76732. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  76733. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  76734. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  76735. }
  76736. // Merge into a single mesh
  76737. var engine = this._source.getScene().getEngine();
  76738. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  76739. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  76740. this._ib = engine.createIndexBuffer(this._linesIndices);
  76741. this._indicesCount = this._linesIndices.length;
  76742. };
  76743. EdgesRenderer.prototype.render = function () {
  76744. var scene = this._source.getScene();
  76745. if (!this._lineShader.isReady() || !scene.activeCamera) {
  76746. return;
  76747. }
  76748. var engine = scene.getEngine();
  76749. this._lineShader._preBind();
  76750. // VBOs
  76751. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  76752. scene.resetCachedMaterial();
  76753. this._lineShader.setColor4("color", this._source.edgesColor);
  76754. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  76755. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  76756. }
  76757. else {
  76758. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  76759. }
  76760. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  76761. this._lineShader.bind(this._source.getWorldMatrix());
  76762. // Draw order
  76763. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  76764. this._lineShader.unbind();
  76765. engine.setDepthWrite(true);
  76766. };
  76767. return EdgesRenderer;
  76768. }());
  76769. BABYLON.EdgesRenderer = EdgesRenderer;
  76770. })(BABYLON || (BABYLON = {}));
  76771. //# sourceMappingURL=babylon.edgesRenderer.js.map
  76772. var BABYLON;
  76773. (function (BABYLON) {
  76774. /**
  76775. * Special Glow Blur post process only blurring the alpha channel
  76776. * It enforces keeping the most luminous color in the color channel.
  76777. */
  76778. var GlowBlurPostProcess = /** @class */ (function (_super) {
  76779. __extends(GlowBlurPostProcess, _super);
  76780. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  76781. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76782. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  76783. _this.direction = direction;
  76784. _this.kernel = kernel;
  76785. _this.onApplyObservable.add(function (effect) {
  76786. effect.setFloat2("screenSize", _this.width, _this.height);
  76787. effect.setVector2("direction", _this.direction);
  76788. effect.setFloat("blurWidth", _this.kernel);
  76789. });
  76790. return _this;
  76791. }
  76792. return GlowBlurPostProcess;
  76793. }(BABYLON.PostProcess));
  76794. /**
  76795. * The highlight layer Helps adding a glow effect around a mesh.
  76796. *
  76797. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  76798. * glowy meshes to your scene.
  76799. *
  76800. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  76801. */
  76802. var HighlightLayer = /** @class */ (function () {
  76803. /**
  76804. * Instantiates a new highlight Layer and references it to the scene..
  76805. * @param name The name of the layer
  76806. * @param scene The scene to use the layer in
  76807. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  76808. */
  76809. function HighlightLayer(name, scene, options) {
  76810. this.name = name;
  76811. this._vertexBuffers = {};
  76812. this._mainTextureDesiredSize = { width: 0, height: 0 };
  76813. this._meshes = {};
  76814. this._maxSize = 0;
  76815. this._shouldRender = false;
  76816. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  76817. this._excludedMeshes = {};
  76818. /**
  76819. * Specifies whether or not the inner glow is ACTIVE in the layer.
  76820. */
  76821. this.innerGlow = true;
  76822. /**
  76823. * Specifies whether or not the outer glow is ACTIVE in the layer.
  76824. */
  76825. this.outerGlow = true;
  76826. /**
  76827. * Specifies wether the highlight layer is enabled or not.
  76828. */
  76829. this.isEnabled = true;
  76830. /**
  76831. * An event triggered when the highlight layer has been disposed.
  76832. * @type {BABYLON.Observable}
  76833. */
  76834. this.onDisposeObservable = new BABYLON.Observable();
  76835. /**
  76836. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  76837. * @type {BABYLON.Observable}
  76838. */
  76839. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  76840. /**
  76841. * An event triggered when the highlight layer is being blurred.
  76842. * @type {BABYLON.Observable}
  76843. */
  76844. this.onBeforeBlurObservable = new BABYLON.Observable();
  76845. /**
  76846. * An event triggered when the highlight layer has been blurred.
  76847. * @type {BABYLON.Observable}
  76848. */
  76849. this.onAfterBlurObservable = new BABYLON.Observable();
  76850. /**
  76851. * An event triggered when the glowing blurred texture is being merged in the scene.
  76852. * @type {BABYLON.Observable}
  76853. */
  76854. this.onBeforeComposeObservable = new BABYLON.Observable();
  76855. /**
  76856. * An event triggered when the glowing blurred texture has been merged in the scene.
  76857. * @type {BABYLON.Observable}
  76858. */
  76859. this.onAfterComposeObservable = new BABYLON.Observable();
  76860. /**
  76861. * An event triggered when the highlight layer changes its size.
  76862. * @type {BABYLON.Observable}
  76863. */
  76864. this.onSizeChangedObservable = new BABYLON.Observable();
  76865. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76866. var engine = scene.getEngine();
  76867. this._engine = engine;
  76868. this._maxSize = this._engine.getCaps().maxTextureSize;
  76869. this._scene.highlightLayers.push(this);
  76870. // Warn on stencil.
  76871. if (!this._engine.isStencilEnable) {
  76872. 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 }");
  76873. }
  76874. // Adapt options
  76875. this._options = options || {
  76876. mainTextureRatio: 0.5,
  76877. blurTextureSizeRatio: 0.5,
  76878. blurHorizontalSize: 1.0,
  76879. blurVerticalSize: 1.0,
  76880. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  76881. camera: null
  76882. };
  76883. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  76884. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  76885. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  76886. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  76887. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  76888. // VBO
  76889. var vertices = [];
  76890. vertices.push(1, 1);
  76891. vertices.push(-1, 1);
  76892. vertices.push(-1, -1);
  76893. vertices.push(1, -1);
  76894. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76895. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  76896. this._createIndexBuffer();
  76897. // Effect
  76898. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  76899. // Render target
  76900. this.setMainTextureSize();
  76901. // Create Textures and post processes
  76902. this.createTextureAndPostProcesses();
  76903. }
  76904. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  76905. /**
  76906. * Gets the horizontal size of the blur.
  76907. */
  76908. get: function () {
  76909. return this._horizontalBlurPostprocess.kernel;
  76910. },
  76911. /**
  76912. * Specifies the horizontal size of the blur.
  76913. */
  76914. set: function (value) {
  76915. this._horizontalBlurPostprocess.kernel = value;
  76916. },
  76917. enumerable: true,
  76918. configurable: true
  76919. });
  76920. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  76921. /**
  76922. * Gets the vertical size of the blur.
  76923. */
  76924. get: function () {
  76925. return this._verticalBlurPostprocess.kernel;
  76926. },
  76927. /**
  76928. * Specifies the vertical size of the blur.
  76929. */
  76930. set: function (value) {
  76931. this._verticalBlurPostprocess.kernel = value;
  76932. },
  76933. enumerable: true,
  76934. configurable: true
  76935. });
  76936. Object.defineProperty(HighlightLayer.prototype, "camera", {
  76937. /**
  76938. * Gets the camera attached to the layer.
  76939. */
  76940. get: function () {
  76941. return this._options.camera;
  76942. },
  76943. enumerable: true,
  76944. configurable: true
  76945. });
  76946. HighlightLayer.prototype._createIndexBuffer = function () {
  76947. var engine = this._scene.getEngine();
  76948. // Indices
  76949. var indices = [];
  76950. indices.push(0);
  76951. indices.push(1);
  76952. indices.push(2);
  76953. indices.push(0);
  76954. indices.push(2);
  76955. indices.push(3);
  76956. this._indexBuffer = engine.createIndexBuffer(indices);
  76957. };
  76958. HighlightLayer.prototype._rebuild = function () {
  76959. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76960. if (vb) {
  76961. vb._rebuild();
  76962. }
  76963. this._createIndexBuffer();
  76964. };
  76965. /**
  76966. * Creates the render target textures and post processes used in the highlight layer.
  76967. */
  76968. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  76969. var _this = this;
  76970. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  76971. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  76972. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  76973. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  76974. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  76975. width: this._mainTextureDesiredSize.width,
  76976. height: this._mainTextureDesiredSize.height
  76977. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76978. this._mainTexture.activeCamera = this._options.camera;
  76979. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76980. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76981. this._mainTexture.anisotropicFilteringLevel = 1;
  76982. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76983. this._mainTexture.renderParticles = false;
  76984. this._mainTexture.renderList = null;
  76985. this._mainTexture.ignoreCameraViewport = true;
  76986. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  76987. width: blurTextureWidth,
  76988. height: blurTextureHeight
  76989. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76990. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76991. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76992. this._blurTexture.anisotropicFilteringLevel = 16;
  76993. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76994. this._blurTexture.renderParticles = false;
  76995. this._blurTexture.ignoreCameraViewport = true;
  76996. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76997. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  76998. effect.setTexture("textureSampler", _this._mainTexture);
  76999. });
  77000. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  77001. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  77002. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  77003. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  77004. });
  77005. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  77006. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  77007. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  77008. });
  77009. }
  77010. else {
  77011. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  77012. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  77013. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  77014. });
  77015. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  77016. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  77017. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  77018. });
  77019. }
  77020. this._mainTexture.onAfterUnbindObservable.add(function () {
  77021. _this.onBeforeBlurObservable.notifyObservers(_this);
  77022. var internalTexture = _this._blurTexture.getInternalTexture();
  77023. if (internalTexture) {
  77024. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  77025. }
  77026. _this.onAfterBlurObservable.notifyObservers(_this);
  77027. });
  77028. // Custom render function
  77029. var renderSubMesh = function (subMesh) {
  77030. if (!_this._meshes) {
  77031. return;
  77032. }
  77033. var material = subMesh.getMaterial();
  77034. var mesh = subMesh.getRenderingMesh();
  77035. var scene = _this._scene;
  77036. var engine = scene.getEngine();
  77037. if (!material) {
  77038. return;
  77039. }
  77040. // Do not block in blend mode.
  77041. if (material.needAlphaBlendingForMesh(mesh)) {
  77042. return;
  77043. }
  77044. // Culling
  77045. engine.setState(material.backFaceCulling);
  77046. // Managing instances
  77047. var batch = mesh._getInstancesRenderList(subMesh._id);
  77048. if (batch.mustReturn) {
  77049. return;
  77050. }
  77051. // Excluded Mesh
  77052. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  77053. return;
  77054. }
  77055. ;
  77056. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  77057. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  77058. var emissiveTexture = null;
  77059. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  77060. emissiveTexture = material.emissiveTexture;
  77061. }
  77062. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  77063. engine.enableEffect(_this._glowMapGenerationEffect);
  77064. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  77065. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  77066. if (highlightLayerMesh) {
  77067. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  77068. }
  77069. else {
  77070. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  77071. }
  77072. // Alpha test
  77073. if (material && material.needAlphaTesting()) {
  77074. var alphaTexture = material.getAlphaTestTexture();
  77075. if (alphaTexture) {
  77076. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  77077. var textureMatrix = alphaTexture.getTextureMatrix();
  77078. if (textureMatrix) {
  77079. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  77080. }
  77081. }
  77082. }
  77083. // Glow emissive only
  77084. if (emissiveTexture) {
  77085. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  77086. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  77087. }
  77088. // Bones
  77089. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77090. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77091. }
  77092. // Draw
  77093. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  77094. }
  77095. else {
  77096. // Need to reset refresh rate of the shadowMap
  77097. _this._mainTexture.resetRefreshCounter();
  77098. }
  77099. };
  77100. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77101. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  77102. var index;
  77103. var engine = _this._scene.getEngine();
  77104. if (depthOnlySubMeshes.length) {
  77105. engine.setColorWrite(false);
  77106. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77107. renderSubMesh(depthOnlySubMeshes.data[index]);
  77108. }
  77109. engine.setColorWrite(true);
  77110. }
  77111. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77112. renderSubMesh(opaqueSubMeshes.data[index]);
  77113. }
  77114. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77115. renderSubMesh(alphaTestSubMeshes.data[index]);
  77116. }
  77117. for (index = 0; index < transparentSubMeshes.length; index++) {
  77118. renderSubMesh(transparentSubMeshes.data[index]);
  77119. }
  77120. };
  77121. this._mainTexture.onClearObservable.add(function (engine) {
  77122. engine.clear(HighlightLayer.neutralColor, true, true, true);
  77123. });
  77124. };
  77125. /**
  77126. * Checks for the readiness of the element composing the layer.
  77127. * @param subMesh the mesh to check for
  77128. * @param useInstances specify wether or not to use instances to render the mesh
  77129. * @param emissiveTexture the associated emissive texture used to generate the glow
  77130. * @return true if ready otherwise, false
  77131. */
  77132. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  77133. var material = subMesh.getMaterial();
  77134. var mesh = subMesh.getRenderingMesh();
  77135. if (!material || !mesh || !this._meshes) {
  77136. return false;
  77137. }
  77138. var emissiveTexture = null;
  77139. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  77140. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  77141. emissiveTexture = material.emissiveTexture;
  77142. }
  77143. return this._isReady(subMesh, useInstances, emissiveTexture);
  77144. };
  77145. /**
  77146. * Checks for the readiness of the element composing the layer.
  77147. * @param subMesh the mesh to check for
  77148. * @param useInstances specify wether or not to use instances to render the mesh
  77149. * @param emissiveTexture the associated emissive texture used to generate the glow
  77150. * @return true if ready otherwise, false
  77151. */
  77152. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  77153. var material = subMesh.getMaterial();
  77154. if (!material) {
  77155. return false;
  77156. }
  77157. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  77158. return false;
  77159. }
  77160. var defines = [];
  77161. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77162. var mesh = subMesh.getMesh();
  77163. var uv1 = false;
  77164. var uv2 = false;
  77165. // Alpha test
  77166. if (material && material.needAlphaTesting()) {
  77167. var alphaTexture = material.getAlphaTestTexture();
  77168. if (alphaTexture) {
  77169. defines.push("#define ALPHATEST");
  77170. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  77171. alphaTexture.coordinatesIndex === 1) {
  77172. defines.push("#define DIFFUSEUV2");
  77173. uv2 = true;
  77174. }
  77175. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77176. defines.push("#define DIFFUSEUV1");
  77177. uv1 = true;
  77178. }
  77179. }
  77180. }
  77181. // Emissive
  77182. if (emissiveTexture) {
  77183. defines.push("#define EMISSIVE");
  77184. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  77185. emissiveTexture.coordinatesIndex === 1) {
  77186. defines.push("#define EMISSIVEUV2");
  77187. uv2 = true;
  77188. }
  77189. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77190. defines.push("#define EMISSIVEUV1");
  77191. uv1 = true;
  77192. }
  77193. }
  77194. if (uv1) {
  77195. attribs.push(BABYLON.VertexBuffer.UVKind);
  77196. defines.push("#define UV1");
  77197. }
  77198. if (uv2) {
  77199. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77200. defines.push("#define UV2");
  77201. }
  77202. // Bones
  77203. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77204. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77205. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77206. if (mesh.numBoneInfluencers > 4) {
  77207. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77208. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77209. }
  77210. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77211. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77212. }
  77213. else {
  77214. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77215. }
  77216. // Instances
  77217. if (useInstances) {
  77218. defines.push("#define INSTANCES");
  77219. attribs.push("world0");
  77220. attribs.push("world1");
  77221. attribs.push("world2");
  77222. attribs.push("world3");
  77223. }
  77224. // Get correct effect
  77225. var join = defines.join("\n");
  77226. if (this._cachedDefines !== join) {
  77227. this._cachedDefines = join;
  77228. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  77229. }
  77230. return this._glowMapGenerationEffect.isReady();
  77231. };
  77232. /**
  77233. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  77234. */
  77235. HighlightLayer.prototype.render = function () {
  77236. var currentEffect = this._glowMapMergeEffect;
  77237. // Check
  77238. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  77239. return;
  77240. var engine = this._scene.getEngine();
  77241. this.onBeforeComposeObservable.notifyObservers(this);
  77242. // Render
  77243. engine.enableEffect(currentEffect);
  77244. engine.setState(false);
  77245. // Cache
  77246. var previousStencilBuffer = engine.getStencilBuffer();
  77247. var previousStencilFunction = engine.getStencilFunction();
  77248. var previousStencilMask = engine.getStencilMask();
  77249. var previousStencilOperationPass = engine.getStencilOperationPass();
  77250. var previousStencilOperationFail = engine.getStencilOperationFail();
  77251. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  77252. var previousAlphaMode = engine.getAlphaMode();
  77253. // Texture
  77254. currentEffect.setTexture("textureSampler", this._blurTexture);
  77255. // VBOs
  77256. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  77257. // Stencil operations
  77258. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  77259. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  77260. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  77261. // Draw order
  77262. engine.setAlphaMode(this._options.alphaBlendingMode);
  77263. engine.setStencilMask(0x00);
  77264. engine.setStencilBuffer(true);
  77265. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  77266. if (this.outerGlow) {
  77267. currentEffect.setFloat("offset", 0);
  77268. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  77269. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77270. }
  77271. if (this.innerGlow) {
  77272. currentEffect.setFloat("offset", 1);
  77273. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  77274. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77275. }
  77276. // Restore Cache
  77277. engine.setStencilFunction(previousStencilFunction);
  77278. engine.setStencilMask(previousStencilMask);
  77279. engine.setAlphaMode(previousAlphaMode);
  77280. engine.setStencilBuffer(previousStencilBuffer);
  77281. engine.setStencilOperationPass(previousStencilOperationPass);
  77282. engine.setStencilOperationFail(previousStencilOperationFail);
  77283. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  77284. engine._stencilState.reset();
  77285. this.onAfterComposeObservable.notifyObservers(this);
  77286. // Handle size changes.
  77287. var size = this._mainTexture.getSize();
  77288. this.setMainTextureSize();
  77289. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  77290. // Recreate RTT and post processes on size change.
  77291. this.onSizeChangedObservable.notifyObservers(this);
  77292. this.disposeTextureAndPostProcesses();
  77293. this.createTextureAndPostProcesses();
  77294. }
  77295. };
  77296. /**
  77297. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  77298. * @param mesh The mesh to exclude from the highlight layer
  77299. */
  77300. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  77301. if (!this._excludedMeshes) {
  77302. return;
  77303. }
  77304. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  77305. if (!meshExcluded) {
  77306. this._excludedMeshes[mesh.uniqueId] = {
  77307. mesh: mesh,
  77308. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  77309. mesh.getEngine().setStencilBuffer(false);
  77310. }),
  77311. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  77312. mesh.getEngine().setStencilBuffer(true);
  77313. }),
  77314. };
  77315. }
  77316. };
  77317. /**
  77318. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  77319. * @param mesh The mesh to highlight
  77320. */
  77321. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  77322. if (!this._excludedMeshes) {
  77323. return;
  77324. }
  77325. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  77326. if (meshExcluded) {
  77327. if (meshExcluded.beforeRender) {
  77328. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  77329. }
  77330. if (meshExcluded.afterRender) {
  77331. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  77332. }
  77333. }
  77334. this._excludedMeshes[mesh.uniqueId] = null;
  77335. };
  77336. /**
  77337. * Determine if a given mesh will be highlighted by the current HighlightLayer
  77338. * @param mesh mesh to test
  77339. * @returns true if the mesh will be highlighted by the current HighlightLayer
  77340. */
  77341. HighlightLayer.prototype.hasMesh = function (mesh) {
  77342. if (!this._meshes) {
  77343. return false;
  77344. }
  77345. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  77346. };
  77347. /**
  77348. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  77349. * @param mesh The mesh to highlight
  77350. * @param color The color of the highlight
  77351. * @param glowEmissiveOnly Extract the glow from the emissive texture
  77352. */
  77353. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  77354. var _this = this;
  77355. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  77356. if (!this._meshes) {
  77357. return;
  77358. }
  77359. var meshHighlight = this._meshes[mesh.uniqueId];
  77360. if (meshHighlight) {
  77361. meshHighlight.color = color;
  77362. }
  77363. else {
  77364. this._meshes[mesh.uniqueId] = {
  77365. mesh: mesh,
  77366. color: color,
  77367. // Lambda required for capture due to Observable this context
  77368. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  77369. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  77370. _this.defaultStencilReference(mesh);
  77371. }
  77372. else {
  77373. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  77374. }
  77375. }),
  77376. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  77377. glowEmissiveOnly: glowEmissiveOnly
  77378. };
  77379. }
  77380. this._shouldRender = true;
  77381. };
  77382. /**
  77383. * Remove a mesh from the highlight layer in order to make it stop glowing.
  77384. * @param mesh The mesh to highlight
  77385. */
  77386. HighlightLayer.prototype.removeMesh = function (mesh) {
  77387. if (!this._meshes) {
  77388. return;
  77389. }
  77390. var meshHighlight = this._meshes[mesh.uniqueId];
  77391. if (meshHighlight) {
  77392. if (meshHighlight.observerHighlight) {
  77393. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  77394. }
  77395. if (meshHighlight.observerDefault) {
  77396. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  77397. }
  77398. delete this._meshes[mesh.uniqueId];
  77399. }
  77400. this._shouldRender = false;
  77401. for (var meshHighlightToCheck in this._meshes) {
  77402. if (this._meshes[meshHighlightToCheck]) {
  77403. this._shouldRender = true;
  77404. break;
  77405. }
  77406. }
  77407. };
  77408. /**
  77409. * Returns true if the layer contains information to display, otherwise false.
  77410. */
  77411. HighlightLayer.prototype.shouldRender = function () {
  77412. return this.isEnabled && this._shouldRender;
  77413. };
  77414. /**
  77415. * Sets the main texture desired size which is the closest power of two
  77416. * of the engine canvas size.
  77417. */
  77418. HighlightLayer.prototype.setMainTextureSize = function () {
  77419. if (this._options.mainTextureFixedSize) {
  77420. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  77421. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  77422. }
  77423. else {
  77424. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  77425. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  77426. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  77427. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  77428. }
  77429. };
  77430. /**
  77431. * Force the stencil to the normal expected value for none glowing parts
  77432. */
  77433. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  77434. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  77435. };
  77436. /**
  77437. * Dispose only the render target textures and post process.
  77438. */
  77439. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  77440. this._blurTexture.dispose();
  77441. this._mainTexture.dispose();
  77442. this._downSamplePostprocess.dispose();
  77443. this._horizontalBlurPostprocess.dispose();
  77444. this._verticalBlurPostprocess.dispose();
  77445. };
  77446. /**
  77447. * Dispose the highlight layer and free resources.
  77448. */
  77449. HighlightLayer.prototype.dispose = function () {
  77450. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77451. if (vertexBuffer) {
  77452. vertexBuffer.dispose();
  77453. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77454. }
  77455. if (this._indexBuffer) {
  77456. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77457. this._indexBuffer = null;
  77458. }
  77459. // Clean textures and post processes
  77460. this.disposeTextureAndPostProcesses();
  77461. if (this._meshes) {
  77462. // Clean mesh references
  77463. for (var id in this._meshes) {
  77464. var meshHighlight = this._meshes[id];
  77465. if (meshHighlight && meshHighlight.mesh) {
  77466. if (meshHighlight.observerHighlight) {
  77467. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  77468. }
  77469. if (meshHighlight.observerDefault) {
  77470. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  77471. }
  77472. }
  77473. }
  77474. this._meshes = null;
  77475. }
  77476. if (this._excludedMeshes) {
  77477. for (var id in this._excludedMeshes) {
  77478. var meshHighlight = this._excludedMeshes[id];
  77479. if (meshHighlight) {
  77480. if (meshHighlight.beforeRender) {
  77481. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  77482. }
  77483. if (meshHighlight.afterRender) {
  77484. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  77485. }
  77486. }
  77487. }
  77488. this._excludedMeshes = null;
  77489. }
  77490. // Remove from scene
  77491. var index = this._scene.highlightLayers.indexOf(this, 0);
  77492. if (index > -1) {
  77493. this._scene.highlightLayers.splice(index, 1);
  77494. }
  77495. // Callback
  77496. this.onDisposeObservable.notifyObservers(this);
  77497. this.onDisposeObservable.clear();
  77498. this.onBeforeRenderMainTextureObservable.clear();
  77499. this.onBeforeBlurObservable.clear();
  77500. this.onBeforeComposeObservable.clear();
  77501. this.onAfterComposeObservable.clear();
  77502. this.onSizeChangedObservable.clear();
  77503. };
  77504. /**
  77505. * The neutral color used during the preparation of the glow effect.
  77506. * This is black by default as the blend operation is a blend operation.
  77507. */
  77508. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  77509. /**
  77510. * Stencil value used for glowing meshes.
  77511. */
  77512. HighlightLayer.glowingMeshStencilReference = 0x02;
  77513. /**
  77514. * Stencil value used for the other meshes in the scene.
  77515. */
  77516. HighlightLayer.normalMeshStencilReference = 0x01;
  77517. return HighlightLayer;
  77518. }());
  77519. BABYLON.HighlightLayer = HighlightLayer;
  77520. })(BABYLON || (BABYLON = {}));
  77521. //# sourceMappingURL=babylon.highlightlayer.js.map
  77522. var BABYLON;
  77523. (function (BABYLON) {
  77524. /**
  77525. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  77526. */
  77527. var AssetTaskState;
  77528. (function (AssetTaskState) {
  77529. /**
  77530. * Initialization
  77531. */
  77532. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  77533. /**
  77534. * Running
  77535. */
  77536. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  77537. /**
  77538. * Done
  77539. */
  77540. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  77541. /**
  77542. * Error
  77543. */
  77544. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  77545. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  77546. /**
  77547. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  77548. */
  77549. var AbstractAssetTask = /** @class */ (function () {
  77550. /**
  77551. * Creates a new {BABYLON.AssetsManager}
  77552. * @param name defines the name of the task
  77553. */
  77554. function AbstractAssetTask(
  77555. /**
  77556. * Task name
  77557. */ name) {
  77558. this.name = name;
  77559. this._isCompleted = false;
  77560. this._taskState = AssetTaskState.INIT;
  77561. }
  77562. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  77563. /**
  77564. * Get if the task is completed
  77565. */
  77566. get: function () {
  77567. return this._isCompleted;
  77568. },
  77569. enumerable: true,
  77570. configurable: true
  77571. });
  77572. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  77573. /**
  77574. * Gets the current state of the task
  77575. */
  77576. get: function () {
  77577. return this._taskState;
  77578. },
  77579. enumerable: true,
  77580. configurable: true
  77581. });
  77582. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  77583. /**
  77584. * Gets the current error object (if task is in error)
  77585. */
  77586. get: function () {
  77587. return this._errorObject;
  77588. },
  77589. enumerable: true,
  77590. configurable: true
  77591. });
  77592. /**
  77593. * Internal only
  77594. * @ignore
  77595. */
  77596. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  77597. if (this._errorObject) {
  77598. return;
  77599. }
  77600. this._errorObject = {
  77601. message: message,
  77602. exception: exception
  77603. };
  77604. };
  77605. /**
  77606. * Execute the current task
  77607. * @param scene defines the scene where you want your assets to be loaded
  77608. * @param onSuccess is a callback called when the task is successfully executed
  77609. * @param onError is a callback called if an error occurs
  77610. */
  77611. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  77612. var _this = this;
  77613. this._taskState = AssetTaskState.RUNNING;
  77614. this.runTask(scene, function () {
  77615. _this.onDoneCallback(onSuccess, onError);
  77616. }, function (msg, exception) {
  77617. _this.onErrorCallback(onError, msg, exception);
  77618. });
  77619. };
  77620. /**
  77621. * Execute the current task
  77622. * @param scene defines the scene where you want your assets to be loaded
  77623. * @param onSuccess is a callback called when the task is successfully executed
  77624. * @param onError is a callback called if an error occurs
  77625. */
  77626. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77627. throw new Error("runTask is not implemented");
  77628. };
  77629. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  77630. this._taskState = AssetTaskState.ERROR;
  77631. this._errorObject = {
  77632. message: message,
  77633. exception: exception
  77634. };
  77635. if (this.onError) {
  77636. this.onError(this, message, exception);
  77637. }
  77638. onError();
  77639. };
  77640. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  77641. try {
  77642. this._taskState = AssetTaskState.DONE;
  77643. this._isCompleted = true;
  77644. if (this.onSuccess) {
  77645. this.onSuccess(this);
  77646. }
  77647. onSuccess();
  77648. }
  77649. catch (e) {
  77650. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  77651. }
  77652. };
  77653. return AbstractAssetTask;
  77654. }());
  77655. BABYLON.AbstractAssetTask = AbstractAssetTask;
  77656. /**
  77657. * Class used to share progress information about assets loading
  77658. */
  77659. var AssetsProgressEvent = /** @class */ (function () {
  77660. /**
  77661. * Creates a {BABYLON.AssetsProgressEvent}
  77662. * @param remainingCount defines the number of remaining tasks to process
  77663. * @param totalCount defines the total number of tasks
  77664. * @param task defines the task that was just processed
  77665. */
  77666. function AssetsProgressEvent(remainingCount, totalCount, task) {
  77667. this.remainingCount = remainingCount;
  77668. this.totalCount = totalCount;
  77669. this.task = task;
  77670. }
  77671. return AssetsProgressEvent;
  77672. }());
  77673. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  77674. /**
  77675. * Define a task used by {BABYLON.AssetsManager} to load meshes
  77676. */
  77677. var MeshAssetTask = /** @class */ (function (_super) {
  77678. __extends(MeshAssetTask, _super);
  77679. /**
  77680. * Creates a new {BABYLON.MeshAssetTask}
  77681. * @param name defines the name of the task
  77682. * @param meshesNames defines the list of mesh's names you want to load
  77683. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  77684. * @param sceneFilename defines the filename of the scene to load from
  77685. */
  77686. function MeshAssetTask(
  77687. /**
  77688. * Defines the name of the task
  77689. */
  77690. name,
  77691. /**
  77692. * Defines the list of mesh's names you want to load
  77693. */
  77694. meshesNames,
  77695. /**
  77696. * Defines the root url to use as a base to load your meshes and associated resources
  77697. */
  77698. rootUrl,
  77699. /**
  77700. * Defines the filename of the scene to load from
  77701. */
  77702. sceneFilename) {
  77703. var _this = _super.call(this, name) || this;
  77704. _this.name = name;
  77705. _this.meshesNames = meshesNames;
  77706. _this.rootUrl = rootUrl;
  77707. _this.sceneFilename = sceneFilename;
  77708. return _this;
  77709. }
  77710. /**
  77711. * Execute the current task
  77712. * @param scene defines the scene where you want your assets to be loaded
  77713. * @param onSuccess is a callback called when the task is successfully executed
  77714. * @param onError is a callback called if an error occurs
  77715. */
  77716. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77717. var _this = this;
  77718. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  77719. _this.loadedMeshes = meshes;
  77720. _this.loadedParticleSystems = particleSystems;
  77721. _this.loadedSkeletons = skeletons;
  77722. onSuccess();
  77723. }, null, function (scene, message, exception) {
  77724. onError(message, exception);
  77725. });
  77726. };
  77727. return MeshAssetTask;
  77728. }(AbstractAssetTask));
  77729. BABYLON.MeshAssetTask = MeshAssetTask;
  77730. /**
  77731. * Define a task used by {BABYLON.AssetsManager} to load text content
  77732. */
  77733. var TextFileAssetTask = /** @class */ (function (_super) {
  77734. __extends(TextFileAssetTask, _super);
  77735. /**
  77736. * Creates a new TextFileAssetTask object
  77737. * @param name defines the name of the task
  77738. * @param url defines the location of the file to load
  77739. */
  77740. function TextFileAssetTask(
  77741. /**
  77742. * Defines the name of the task
  77743. */
  77744. name,
  77745. /**
  77746. * Defines the location of the file to load
  77747. */
  77748. url) {
  77749. var _this = _super.call(this, name) || this;
  77750. _this.name = name;
  77751. _this.url = url;
  77752. return _this;
  77753. }
  77754. /**
  77755. * Execute the current task
  77756. * @param scene defines the scene where you want your assets to be loaded
  77757. * @param onSuccess is a callback called when the task is successfully executed
  77758. * @param onError is a callback called if an error occurs
  77759. */
  77760. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77761. var _this = this;
  77762. scene._loadFile(this.url, function (data) {
  77763. _this.text = data;
  77764. onSuccess();
  77765. }, undefined, false, true, function (request, exception) {
  77766. if (request) {
  77767. onError(request.status + " " + request.statusText, exception);
  77768. }
  77769. });
  77770. };
  77771. return TextFileAssetTask;
  77772. }(AbstractAssetTask));
  77773. BABYLON.TextFileAssetTask = TextFileAssetTask;
  77774. /**
  77775. * Define a task used by {BABYLON.AssetsManager} to load binary data
  77776. */
  77777. var BinaryFileAssetTask = /** @class */ (function (_super) {
  77778. __extends(BinaryFileAssetTask, _super);
  77779. /**
  77780. * Creates a new BinaryFileAssetTask object
  77781. * @param name defines the name of the new task
  77782. * @param url defines the location of the file to load
  77783. */
  77784. function BinaryFileAssetTask(
  77785. /**
  77786. * Defines the name of the task
  77787. */
  77788. name,
  77789. /**
  77790. * Defines the location of the file to load
  77791. */
  77792. url) {
  77793. var _this = _super.call(this, name) || this;
  77794. _this.name = name;
  77795. _this.url = url;
  77796. return _this;
  77797. }
  77798. /**
  77799. * Execute the current task
  77800. * @param scene defines the scene where you want your assets to be loaded
  77801. * @param onSuccess is a callback called when the task is successfully executed
  77802. * @param onError is a callback called if an error occurs
  77803. */
  77804. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77805. var _this = this;
  77806. scene._loadFile(this.url, function (data) {
  77807. _this.data = data;
  77808. onSuccess();
  77809. }, undefined, true, true, function (request, exception) {
  77810. if (request) {
  77811. onError(request.status + " " + request.statusText, exception);
  77812. }
  77813. });
  77814. };
  77815. return BinaryFileAssetTask;
  77816. }(AbstractAssetTask));
  77817. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  77818. /**
  77819. * Define a task used by {BABYLON.AssetsManager} to load images
  77820. */
  77821. var ImageAssetTask = /** @class */ (function (_super) {
  77822. __extends(ImageAssetTask, _super);
  77823. /**
  77824. * Creates a new ImageAssetTask
  77825. * @param name defines the name of the task
  77826. * @param url defines the location of the image to load
  77827. */
  77828. function ImageAssetTask(
  77829. /**
  77830. * Defines the name of the task
  77831. */
  77832. name,
  77833. /**
  77834. * Defines the location of the image to load
  77835. */
  77836. url) {
  77837. var _this = _super.call(this, name) || this;
  77838. _this.name = name;
  77839. _this.url = url;
  77840. return _this;
  77841. }
  77842. /**
  77843. * Execute the current task
  77844. * @param scene defines the scene where you want your assets to be loaded
  77845. * @param onSuccess is a callback called when the task is successfully executed
  77846. * @param onError is a callback called if an error occurs
  77847. */
  77848. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77849. var _this = this;
  77850. var img = new Image();
  77851. BABYLON.Tools.SetCorsBehavior(this.url, img);
  77852. img.onload = function () {
  77853. _this.image = img;
  77854. onSuccess();
  77855. };
  77856. img.onerror = function (err) {
  77857. onError("Error loading image", err);
  77858. };
  77859. img.src = this.url;
  77860. };
  77861. return ImageAssetTask;
  77862. }(AbstractAssetTask));
  77863. BABYLON.ImageAssetTask = ImageAssetTask;
  77864. /**
  77865. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  77866. */
  77867. var TextureAssetTask = /** @class */ (function (_super) {
  77868. __extends(TextureAssetTask, _super);
  77869. /**
  77870. * Creates a new TextureAssetTask object
  77871. * @param name defines the name of the task
  77872. * @param url defines the location of the file to load
  77873. * @param noMipmap defines if mipmap should not be generated (default is false)
  77874. * @param invertY defines if texture must be inverted on Y axis (default is false)
  77875. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  77876. */
  77877. function TextureAssetTask(
  77878. /**
  77879. * Defines the name of the task
  77880. */
  77881. name,
  77882. /**
  77883. * Defines the location of the file to load
  77884. */
  77885. url,
  77886. /**
  77887. * Defines if mipmap should not be generated (default is false)
  77888. */
  77889. noMipmap,
  77890. /**
  77891. * Defines if texture must be inverted on Y axis (default is false)
  77892. */
  77893. invertY,
  77894. /**
  77895. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  77896. */
  77897. samplingMode) {
  77898. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  77899. var _this = _super.call(this, name) || this;
  77900. _this.name = name;
  77901. _this.url = url;
  77902. _this.noMipmap = noMipmap;
  77903. _this.invertY = invertY;
  77904. _this.samplingMode = samplingMode;
  77905. return _this;
  77906. }
  77907. /**
  77908. * Execute the current task
  77909. * @param scene defines the scene where you want your assets to be loaded
  77910. * @param onSuccess is a callback called when the task is successfully executed
  77911. * @param onError is a callback called if an error occurs
  77912. */
  77913. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77914. var onload = function () {
  77915. onSuccess();
  77916. };
  77917. var onerror = function (message, exception) {
  77918. onError(message, exception);
  77919. };
  77920. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  77921. };
  77922. return TextureAssetTask;
  77923. }(AbstractAssetTask));
  77924. BABYLON.TextureAssetTask = TextureAssetTask;
  77925. /**
  77926. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  77927. */
  77928. var CubeTextureAssetTask = /** @class */ (function (_super) {
  77929. __extends(CubeTextureAssetTask, _super);
  77930. /**
  77931. * Creates a new CubeTextureAssetTask
  77932. * @param name defines the name of the task
  77933. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  77934. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  77935. * @param noMipmap defines if mipmaps should not be generated (default is false)
  77936. * @param files defines the explicit list of files (undefined by default)
  77937. */
  77938. function CubeTextureAssetTask(
  77939. /**
  77940. * Defines the name of the task
  77941. */
  77942. name,
  77943. /**
  77944. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  77945. */
  77946. url,
  77947. /**
  77948. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  77949. */
  77950. extensions,
  77951. /**
  77952. * Defines if mipmaps should not be generated (default is false)
  77953. */
  77954. noMipmap,
  77955. /**
  77956. * Defines the explicit list of files (undefined by default)
  77957. */
  77958. files) {
  77959. var _this = _super.call(this, name) || this;
  77960. _this.name = name;
  77961. _this.url = url;
  77962. _this.extensions = extensions;
  77963. _this.noMipmap = noMipmap;
  77964. _this.files = files;
  77965. return _this;
  77966. }
  77967. /**
  77968. * Execute the current task
  77969. * @param scene defines the scene where you want your assets to be loaded
  77970. * @param onSuccess is a callback called when the task is successfully executed
  77971. * @param onError is a callback called if an error occurs
  77972. */
  77973. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77974. var onload = function () {
  77975. onSuccess();
  77976. };
  77977. var onerror = function (message, exception) {
  77978. onError(message, exception);
  77979. };
  77980. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  77981. };
  77982. return CubeTextureAssetTask;
  77983. }(AbstractAssetTask));
  77984. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  77985. /**
  77986. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  77987. */
  77988. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  77989. __extends(HDRCubeTextureAssetTask, _super);
  77990. /**
  77991. * Creates a new HDRCubeTextureAssetTask object
  77992. * @param name defines the name of the task
  77993. * @param url defines the location of the file to load
  77994. * @param size defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  77995. * @param noMipmap defines if mipmaps should not be generated (default is false)
  77996. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  77997. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  77998. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  77999. */
  78000. function HDRCubeTextureAssetTask(
  78001. /**
  78002. * Defines the name of the task
  78003. */
  78004. name,
  78005. /**
  78006. * Defines the location of the file to load
  78007. */
  78008. url,
  78009. /**
  78010. * Defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  78011. */
  78012. size,
  78013. /**
  78014. * Defines if mipmaps should not be generated (default is false)
  78015. */
  78016. noMipmap,
  78017. /**
  78018. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  78019. */
  78020. generateHarmonics,
  78021. /**
  78022. * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  78023. */
  78024. useInGammaSpace,
  78025. /**
  78026. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  78027. */
  78028. usePMREMGenerator) {
  78029. if (noMipmap === void 0) { noMipmap = false; }
  78030. if (generateHarmonics === void 0) { generateHarmonics = true; }
  78031. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  78032. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  78033. var _this = _super.call(this, name) || this;
  78034. _this.name = name;
  78035. _this.url = url;
  78036. _this.size = size;
  78037. _this.noMipmap = noMipmap;
  78038. _this.generateHarmonics = generateHarmonics;
  78039. _this.useInGammaSpace = useInGammaSpace;
  78040. _this.usePMREMGenerator = usePMREMGenerator;
  78041. return _this;
  78042. }
  78043. /**
  78044. * Execute the current task
  78045. * @param scene defines the scene where you want your assets to be loaded
  78046. * @param onSuccess is a callback called when the task is successfully executed
  78047. * @param onError is a callback called if an error occurs
  78048. */
  78049. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  78050. var onload = function () {
  78051. onSuccess();
  78052. };
  78053. var onerror = function (message, exception) {
  78054. onError(message, exception);
  78055. };
  78056. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  78057. };
  78058. return HDRCubeTextureAssetTask;
  78059. }(AbstractAssetTask));
  78060. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  78061. /**
  78062. * This class can be used to easily import assets into a scene
  78063. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  78064. */
  78065. var AssetsManager = /** @class */ (function () {
  78066. /**
  78067. * Creates a new AssetsManager
  78068. * @param scene defines the scene to work on
  78069. */
  78070. function AssetsManager(scene) {
  78071. this._isLoading = false;
  78072. this._tasks = new Array();
  78073. this._waitingTasksCount = 0;
  78074. this._totalTasksCount = 0;
  78075. /**
  78076. * Observable called when all tasks are processed
  78077. */
  78078. this.onTaskSuccessObservable = new BABYLON.Observable();
  78079. /**
  78080. * Observable called when a task had an error
  78081. */
  78082. this.onTaskErrorObservable = new BABYLON.Observable();
  78083. /**
  78084. * Observable called when a task is successful
  78085. */
  78086. this.onTasksDoneObservable = new BABYLON.Observable();
  78087. /**
  78088. * Observable called when a task is done (whatever the result is)
  78089. */
  78090. this.onProgressObservable = new BABYLON.Observable();
  78091. /**
  78092. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  78093. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  78094. */
  78095. this.useDefaultLoadingScreen = true;
  78096. this._scene = scene;
  78097. }
  78098. /**
  78099. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  78100. * @param taskName defines the name of the new task
  78101. * @param meshesNames defines the name of meshes to load
  78102. * @param rootUrl defines the root url to use to locate files
  78103. * @param sceneFilename defines the filename of the scene file
  78104. * @returns a new {BABYLON.MeshAssetTask} object
  78105. */
  78106. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  78107. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  78108. this._tasks.push(task);
  78109. return task;
  78110. };
  78111. /**
  78112. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  78113. * @param taskName defines the name of the new task
  78114. * @param url defines the url of the file to load
  78115. * @returns a new {BABYLON.TextFileAssetTask} object
  78116. */
  78117. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  78118. var task = new TextFileAssetTask(taskName, url);
  78119. this._tasks.push(task);
  78120. return task;
  78121. };
  78122. /**
  78123. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  78124. * @param taskName defines the name of the new task
  78125. * @param url defines the url of the file to load
  78126. * @returns a new {BABYLON.BinaryFileAssetTask} object
  78127. */
  78128. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  78129. var task = new BinaryFileAssetTask(taskName, url);
  78130. this._tasks.push(task);
  78131. return task;
  78132. };
  78133. /**
  78134. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  78135. * @param taskName defines the name of the new task
  78136. * @param url defines the url of the file to load
  78137. * @returns a new {BABYLON.ImageAssetTask} object
  78138. */
  78139. AssetsManager.prototype.addImageTask = function (taskName, url) {
  78140. var task = new ImageAssetTask(taskName, url);
  78141. this._tasks.push(task);
  78142. return task;
  78143. };
  78144. /**
  78145. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  78146. * @param taskName defines the name of the new task
  78147. * @param url defines the url of the file to load
  78148. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  78149. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  78150. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  78151. * @returns a new {BABYLON.TextureAssetTask} object
  78152. */
  78153. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  78154. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  78155. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  78156. this._tasks.push(task);
  78157. return task;
  78158. };
  78159. /**
  78160. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  78161. * @param taskName defines the name of the new task
  78162. * @param url defines the url of the file to load
  78163. * @param extensions defines the extension to use to load the cube map (can be null)
  78164. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  78165. * @param files defines the list of files to load (can be null)
  78166. * @returns a new {BABYLON.CubeTextureAssetTask} object
  78167. */
  78168. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  78169. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  78170. this._tasks.push(task);
  78171. return task;
  78172. };
  78173. /**
  78174. *
  78175. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  78176. * @param taskName defines the name of the new task
  78177. * @param url defines the url of the file to load
  78178. * @param size defines the size you want for the cubemap (can be null)
  78179. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  78180. * @param generateHarmonics defines if you want to automatically generate (true by default)
  78181. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  78182. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  78183. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  78184. */
  78185. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  78186. if (noMipmap === void 0) { noMipmap = false; }
  78187. if (generateHarmonics === void 0) { generateHarmonics = true; }
  78188. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  78189. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  78190. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  78191. this._tasks.push(task);
  78192. return task;
  78193. };
  78194. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  78195. var _this = this;
  78196. this._waitingTasksCount--;
  78197. try {
  78198. if (task.taskState === AssetTaskState.DONE) {
  78199. // Let's remove successfull tasks
  78200. BABYLON.Tools.SetImmediate(function () {
  78201. var index = _this._tasks.indexOf(task);
  78202. if (index > -1) {
  78203. _this._tasks.splice(index, 1);
  78204. }
  78205. });
  78206. }
  78207. if (this.onProgress) {
  78208. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  78209. }
  78210. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  78211. }
  78212. catch (e) {
  78213. BABYLON.Tools.Error("Error running progress callbacks.");
  78214. console.log(e);
  78215. }
  78216. if (this._waitingTasksCount === 0) {
  78217. try {
  78218. if (this.onFinish) {
  78219. this.onFinish(this._tasks);
  78220. }
  78221. this.onTasksDoneObservable.notifyObservers(this._tasks);
  78222. }
  78223. catch (e) {
  78224. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  78225. console.log(e);
  78226. }
  78227. this._isLoading = false;
  78228. this._scene.getEngine().hideLoadingUI();
  78229. }
  78230. };
  78231. AssetsManager.prototype._runTask = function (task) {
  78232. var _this = this;
  78233. var done = function () {
  78234. try {
  78235. if (_this.onTaskSuccess) {
  78236. _this.onTaskSuccess(task);
  78237. }
  78238. _this.onTaskSuccessObservable.notifyObservers(task);
  78239. _this._decreaseWaitingTasksCount(task);
  78240. }
  78241. catch (e) {
  78242. error("Error executing task success callbacks", e);
  78243. }
  78244. };
  78245. var error = function (message, exception) {
  78246. task._setErrorObject(message, exception);
  78247. if (_this.onTaskError) {
  78248. _this.onTaskError(task);
  78249. }
  78250. _this.onTaskErrorObservable.notifyObservers(task);
  78251. _this._decreaseWaitingTasksCount(task);
  78252. };
  78253. task.run(this._scene, done, error);
  78254. };
  78255. /**
  78256. * Reset the {BABYLON.AssetsManager} and remove all tasks
  78257. * @return the current instance of the {BABYLON.AssetsManager}
  78258. */
  78259. AssetsManager.prototype.reset = function () {
  78260. this._isLoading = false;
  78261. this._tasks = new Array();
  78262. return this;
  78263. };
  78264. /**
  78265. * Start the loading process
  78266. * @return the current instance of the {BABYLON.AssetsManager}
  78267. */
  78268. AssetsManager.prototype.load = function () {
  78269. if (this._isLoading) {
  78270. return this;
  78271. }
  78272. this._isLoading = true;
  78273. this._waitingTasksCount = this._tasks.length;
  78274. this._totalTasksCount = this._tasks.length;
  78275. if (this._waitingTasksCount === 0) {
  78276. if (this.onFinish) {
  78277. this.onFinish(this._tasks);
  78278. }
  78279. this.onTasksDoneObservable.notifyObservers(this._tasks);
  78280. return this;
  78281. }
  78282. if (this.useDefaultLoadingScreen) {
  78283. this._scene.getEngine().displayLoadingUI();
  78284. }
  78285. for (var index = 0; index < this._tasks.length; index++) {
  78286. var task = this._tasks[index];
  78287. this._runTask(task);
  78288. }
  78289. return this;
  78290. };
  78291. return AssetsManager;
  78292. }());
  78293. BABYLON.AssetsManager = AssetsManager;
  78294. })(BABYLON || (BABYLON = {}));
  78295. //# sourceMappingURL=babylon.assetsManager.js.map
  78296. var BABYLON;
  78297. (function (BABYLON) {
  78298. var serializedGeometries = [];
  78299. var serializeGeometry = function (geometry, serializationGeometries) {
  78300. if (serializedGeometries[geometry.id]) {
  78301. return;
  78302. }
  78303. if (geometry.doNotSerialize) {
  78304. return;
  78305. }
  78306. if (geometry instanceof BABYLON.BoxGeometry) {
  78307. serializationGeometries.boxes.push(geometry.serialize());
  78308. }
  78309. else if (geometry instanceof BABYLON.SphereGeometry) {
  78310. serializationGeometries.spheres.push(geometry.serialize());
  78311. }
  78312. else if (geometry instanceof BABYLON.CylinderGeometry) {
  78313. serializationGeometries.cylinders.push(geometry.serialize());
  78314. }
  78315. else if (geometry instanceof BABYLON.TorusGeometry) {
  78316. serializationGeometries.toruses.push(geometry.serialize());
  78317. }
  78318. else if (geometry instanceof BABYLON.GroundGeometry) {
  78319. serializationGeometries.grounds.push(geometry.serialize());
  78320. }
  78321. else if (geometry instanceof BABYLON.Plane) {
  78322. serializationGeometries.planes.push(geometry.serialize());
  78323. }
  78324. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  78325. serializationGeometries.torusKnots.push(geometry.serialize());
  78326. }
  78327. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  78328. throw new Error("Unknown primitive type");
  78329. }
  78330. else {
  78331. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  78332. }
  78333. serializedGeometries[geometry.id] = true;
  78334. };
  78335. var serializeMesh = function (mesh, serializationScene) {
  78336. var serializationObject = {};
  78337. // Geometry
  78338. var geometry = mesh._geometry;
  78339. if (geometry) {
  78340. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  78341. // 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
  78342. serializeGeometry(geometry, serializationScene.geometries);
  78343. }
  78344. }
  78345. // Custom
  78346. if (mesh.serialize) {
  78347. mesh.serialize(serializationObject);
  78348. }
  78349. return serializationObject;
  78350. };
  78351. var finalizeSingleMesh = function (mesh, serializationObject) {
  78352. //only works if the mesh is already loaded
  78353. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  78354. //serialize material
  78355. if (mesh.material) {
  78356. if (mesh.material instanceof BABYLON.StandardMaterial) {
  78357. serializationObject.materials = serializationObject.materials || [];
  78358. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  78359. serializationObject.materials.push(mesh.material.serialize());
  78360. }
  78361. }
  78362. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  78363. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  78364. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  78365. serializationObject.multiMaterials.push(mesh.material.serialize());
  78366. }
  78367. }
  78368. }
  78369. //serialize geometry
  78370. var geometry = mesh._geometry;
  78371. if (geometry) {
  78372. if (!serializationObject.geometries) {
  78373. serializationObject.geometries = {};
  78374. serializationObject.geometries.boxes = [];
  78375. serializationObject.geometries.spheres = [];
  78376. serializationObject.geometries.cylinders = [];
  78377. serializationObject.geometries.toruses = [];
  78378. serializationObject.geometries.grounds = [];
  78379. serializationObject.geometries.planes = [];
  78380. serializationObject.geometries.torusKnots = [];
  78381. serializationObject.geometries.vertexData = [];
  78382. }
  78383. serializeGeometry(geometry, serializationObject.geometries);
  78384. }
  78385. // Skeletons
  78386. if (mesh.skeleton) {
  78387. serializationObject.skeletons = serializationObject.skeletons || [];
  78388. serializationObject.skeletons.push(mesh.skeleton.serialize());
  78389. }
  78390. //serialize the actual mesh
  78391. serializationObject.meshes = serializationObject.meshes || [];
  78392. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  78393. }
  78394. };
  78395. var SceneSerializer = /** @class */ (function () {
  78396. function SceneSerializer() {
  78397. }
  78398. SceneSerializer.ClearCache = function () {
  78399. serializedGeometries = [];
  78400. };
  78401. SceneSerializer.Serialize = function (scene) {
  78402. var serializationObject = {};
  78403. SceneSerializer.ClearCache();
  78404. // Scene
  78405. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  78406. serializationObject.autoClear = scene.autoClear;
  78407. serializationObject.clearColor = scene.clearColor.asArray();
  78408. serializationObject.ambientColor = scene.ambientColor.asArray();
  78409. serializationObject.gravity = scene.gravity.asArray();
  78410. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  78411. serializationObject.workerCollisions = scene.workerCollisions;
  78412. // Fog
  78413. if (scene.fogMode && scene.fogMode !== 0) {
  78414. serializationObject.fogMode = scene.fogMode;
  78415. serializationObject.fogColor = scene.fogColor.asArray();
  78416. serializationObject.fogStart = scene.fogStart;
  78417. serializationObject.fogEnd = scene.fogEnd;
  78418. serializationObject.fogDensity = scene.fogDensity;
  78419. }
  78420. //Physics
  78421. if (scene.isPhysicsEnabled()) {
  78422. var physicEngine = scene.getPhysicsEngine();
  78423. if (physicEngine) {
  78424. serializationObject.physicsEnabled = true;
  78425. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  78426. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  78427. }
  78428. }
  78429. // Metadata
  78430. if (scene.metadata) {
  78431. serializationObject.metadata = scene.metadata;
  78432. }
  78433. // Morph targets
  78434. serializationObject.morphTargetManagers = [];
  78435. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  78436. var abstractMesh = _a[_i];
  78437. var manager = abstractMesh.morphTargetManager;
  78438. if (manager) {
  78439. serializationObject.morphTargetManagers.push(manager.serialize());
  78440. }
  78441. }
  78442. // Lights
  78443. serializationObject.lights = [];
  78444. var index;
  78445. var light;
  78446. for (index = 0; index < scene.lights.length; index++) {
  78447. light = scene.lights[index];
  78448. if (!light.doNotSerialize) {
  78449. serializationObject.lights.push(light.serialize());
  78450. }
  78451. }
  78452. // Cameras
  78453. serializationObject.cameras = [];
  78454. for (index = 0; index < scene.cameras.length; index++) {
  78455. var camera = scene.cameras[index];
  78456. if (!camera.doNotSerialize) {
  78457. serializationObject.cameras.push(camera.serialize());
  78458. }
  78459. }
  78460. if (scene.activeCamera) {
  78461. serializationObject.activeCameraID = scene.activeCamera.id;
  78462. }
  78463. // Animations
  78464. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  78465. // Materials
  78466. serializationObject.materials = [];
  78467. serializationObject.multiMaterials = [];
  78468. var material;
  78469. for (index = 0; index < scene.materials.length; index++) {
  78470. material = scene.materials[index];
  78471. if (!material.doNotSerialize) {
  78472. serializationObject.materials.push(material.serialize());
  78473. }
  78474. }
  78475. // MultiMaterials
  78476. serializationObject.multiMaterials = [];
  78477. for (index = 0; index < scene.multiMaterials.length; index++) {
  78478. var multiMaterial = scene.multiMaterials[index];
  78479. serializationObject.multiMaterials.push(multiMaterial.serialize());
  78480. }
  78481. // Environment texture
  78482. if (scene.environmentTexture) {
  78483. serializationObject.environmentTexture = scene.environmentTexture.name;
  78484. }
  78485. // Skeletons
  78486. serializationObject.skeletons = [];
  78487. for (index = 0; index < scene.skeletons.length; index++) {
  78488. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  78489. }
  78490. // Transform nodes
  78491. serializationObject.transformNodes = [];
  78492. for (index = 0; index < scene.transformNodes.length; index++) {
  78493. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  78494. }
  78495. // Geometries
  78496. serializationObject.geometries = {};
  78497. serializationObject.geometries.boxes = [];
  78498. serializationObject.geometries.spheres = [];
  78499. serializationObject.geometries.cylinders = [];
  78500. serializationObject.geometries.toruses = [];
  78501. serializationObject.geometries.grounds = [];
  78502. serializationObject.geometries.planes = [];
  78503. serializationObject.geometries.torusKnots = [];
  78504. serializationObject.geometries.vertexData = [];
  78505. serializedGeometries = [];
  78506. var geometries = scene.getGeometries();
  78507. for (index = 0; index < geometries.length; index++) {
  78508. var geometry = geometries[index];
  78509. if (geometry.isReady()) {
  78510. serializeGeometry(geometry, serializationObject.geometries);
  78511. }
  78512. }
  78513. // Meshes
  78514. serializationObject.meshes = [];
  78515. for (index = 0; index < scene.meshes.length; index++) {
  78516. var abstractMesh = scene.meshes[index];
  78517. if (abstractMesh instanceof BABYLON.Mesh) {
  78518. var mesh = abstractMesh;
  78519. if (!mesh.doNotSerialize) {
  78520. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  78521. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  78522. }
  78523. }
  78524. }
  78525. }
  78526. // Particles Systems
  78527. serializationObject.particleSystems = [];
  78528. for (index = 0; index < scene.particleSystems.length; index++) {
  78529. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  78530. }
  78531. // Lens flares
  78532. serializationObject.lensFlareSystems = [];
  78533. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  78534. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  78535. }
  78536. // Shadows
  78537. serializationObject.shadowGenerators = [];
  78538. for (index = 0; index < scene.lights.length; index++) {
  78539. light = scene.lights[index];
  78540. var shadowGenerator = light.getShadowGenerator();
  78541. if (shadowGenerator) {
  78542. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  78543. }
  78544. }
  78545. // Action Manager
  78546. if (scene.actionManager) {
  78547. serializationObject.actions = scene.actionManager.serialize("scene");
  78548. }
  78549. // Audio
  78550. serializationObject.sounds = [];
  78551. for (index = 0; index < scene.soundTracks.length; index++) {
  78552. var soundtrack = scene.soundTracks[index];
  78553. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  78554. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  78555. }
  78556. }
  78557. return serializationObject;
  78558. };
  78559. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  78560. if (withParents === void 0) { withParents = false; }
  78561. if (withChildren === void 0) { withChildren = false; }
  78562. var serializationObject = {};
  78563. SceneSerializer.ClearCache();
  78564. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  78565. if (withParents || withChildren) {
  78566. //deliberate for loop! not for each, appended should be processed as well.
  78567. for (var i = 0; i < toSerialize.length; ++i) {
  78568. if (withChildren) {
  78569. toSerialize[i].getDescendants().forEach(function (node) {
  78570. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  78571. toSerialize.push(node);
  78572. }
  78573. });
  78574. }
  78575. //make sure the array doesn't contain the object already
  78576. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  78577. toSerialize.push(toSerialize[i].parent);
  78578. }
  78579. }
  78580. }
  78581. toSerialize.forEach(function (mesh) {
  78582. finalizeSingleMesh(mesh, serializationObject);
  78583. });
  78584. return serializationObject;
  78585. };
  78586. return SceneSerializer;
  78587. }());
  78588. BABYLON.SceneSerializer = SceneSerializer;
  78589. })(BABYLON || (BABYLON = {}));
  78590. //# sourceMappingURL=babylon.sceneSerializer.js.map
  78591. var BABYLON;
  78592. (function (BABYLON) {
  78593. var ReflectionProbe = /** @class */ (function () {
  78594. function ReflectionProbe(name, size, scene, generateMipMaps) {
  78595. if (generateMipMaps === void 0) { generateMipMaps = true; }
  78596. var _this = this;
  78597. this.name = name;
  78598. this._viewMatrix = BABYLON.Matrix.Identity();
  78599. this._target = BABYLON.Vector3.Zero();
  78600. this._add = BABYLON.Vector3.Zero();
  78601. this.invertYAxis = false;
  78602. this.position = BABYLON.Vector3.Zero();
  78603. this._scene = scene;
  78604. this._scene.reflectionProbes.push(this);
  78605. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  78606. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  78607. switch (faceIndex) {
  78608. case 0:
  78609. _this._add.copyFromFloats(1, 0, 0);
  78610. break;
  78611. case 1:
  78612. _this._add.copyFromFloats(-1, 0, 0);
  78613. break;
  78614. case 2:
  78615. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  78616. break;
  78617. case 3:
  78618. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  78619. break;
  78620. case 4:
  78621. _this._add.copyFromFloats(0, 0, 1);
  78622. break;
  78623. case 5:
  78624. _this._add.copyFromFloats(0, 0, -1);
  78625. break;
  78626. }
  78627. if (_this._attachedMesh) {
  78628. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  78629. }
  78630. _this.position.addToRef(_this._add, _this._target);
  78631. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  78632. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  78633. scene._forcedViewPosition = _this.position;
  78634. });
  78635. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  78636. scene._forcedViewPosition = null;
  78637. scene.updateTransformMatrix(true);
  78638. });
  78639. if (scene.activeCamera) {
  78640. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  78641. }
  78642. }
  78643. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  78644. get: function () {
  78645. return this._renderTargetTexture.samples;
  78646. },
  78647. set: function (value) {
  78648. this._renderTargetTexture.samples = value;
  78649. },
  78650. enumerable: true,
  78651. configurable: true
  78652. });
  78653. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  78654. get: function () {
  78655. return this._renderTargetTexture.refreshRate;
  78656. },
  78657. set: function (value) {
  78658. this._renderTargetTexture.refreshRate = value;
  78659. },
  78660. enumerable: true,
  78661. configurable: true
  78662. });
  78663. ReflectionProbe.prototype.getScene = function () {
  78664. return this._scene;
  78665. };
  78666. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  78667. get: function () {
  78668. return this._renderTargetTexture;
  78669. },
  78670. enumerable: true,
  78671. configurable: true
  78672. });
  78673. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  78674. get: function () {
  78675. return this._renderTargetTexture.renderList;
  78676. },
  78677. enumerable: true,
  78678. configurable: true
  78679. });
  78680. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  78681. this._attachedMesh = mesh;
  78682. };
  78683. /**
  78684. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  78685. *
  78686. * @param renderingGroupId The rendering group id corresponding to its index
  78687. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  78688. */
  78689. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  78690. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  78691. };
  78692. ReflectionProbe.prototype.dispose = function () {
  78693. var index = this._scene.reflectionProbes.indexOf(this);
  78694. if (index !== -1) {
  78695. // Remove from the scene if found
  78696. this._scene.reflectionProbes.splice(index, 1);
  78697. }
  78698. if (this._renderTargetTexture) {
  78699. this._renderTargetTexture.dispose();
  78700. this._renderTargetTexture = null;
  78701. }
  78702. };
  78703. return ReflectionProbe;
  78704. }());
  78705. BABYLON.ReflectionProbe = ReflectionProbe;
  78706. })(BABYLON || (BABYLON = {}));
  78707. //# sourceMappingURL=babylon.reflectionProbe.js.map
  78708. var BABYLON;
  78709. (function (BABYLON) {
  78710. var Layer = /** @class */ (function () {
  78711. function Layer(name, imgUrl, scene, isBackground, color) {
  78712. this.name = name;
  78713. this.scale = new BABYLON.Vector2(1, 1);
  78714. this.offset = new BABYLON.Vector2(0, 0);
  78715. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  78716. this.layerMask = 0x0FFFFFFF;
  78717. this._vertexBuffers = {};
  78718. // Events
  78719. /**
  78720. * An event triggered when the layer is disposed.
  78721. * @type {BABYLON.Observable}
  78722. */
  78723. this.onDisposeObservable = new BABYLON.Observable();
  78724. /**
  78725. * An event triggered before rendering the scene
  78726. * @type {BABYLON.Observable}
  78727. */
  78728. this.onBeforeRenderObservable = new BABYLON.Observable();
  78729. /**
  78730. * An event triggered after rendering the scene
  78731. * @type {BABYLON.Observable}
  78732. */
  78733. this.onAfterRenderObservable = new BABYLON.Observable();
  78734. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  78735. this.isBackground = isBackground === undefined ? true : isBackground;
  78736. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  78737. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  78738. this._scene.layers.push(this);
  78739. var engine = this._scene.getEngine();
  78740. // VBO
  78741. var vertices = [];
  78742. vertices.push(1, 1);
  78743. vertices.push(-1, 1);
  78744. vertices.push(-1, -1);
  78745. vertices.push(1, -1);
  78746. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  78747. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  78748. this._createIndexBuffer();
  78749. // Effects
  78750. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  78751. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  78752. }
  78753. Object.defineProperty(Layer.prototype, "onDispose", {
  78754. set: function (callback) {
  78755. if (this._onDisposeObserver) {
  78756. this.onDisposeObservable.remove(this._onDisposeObserver);
  78757. }
  78758. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  78759. },
  78760. enumerable: true,
  78761. configurable: true
  78762. });
  78763. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  78764. set: function (callback) {
  78765. if (this._onBeforeRenderObserver) {
  78766. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  78767. }
  78768. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  78769. },
  78770. enumerable: true,
  78771. configurable: true
  78772. });
  78773. Object.defineProperty(Layer.prototype, "onAfterRender", {
  78774. set: function (callback) {
  78775. if (this._onAfterRenderObserver) {
  78776. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  78777. }
  78778. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  78779. },
  78780. enumerable: true,
  78781. configurable: true
  78782. });
  78783. Layer.prototype._createIndexBuffer = function () {
  78784. var engine = this._scene.getEngine();
  78785. // Indices
  78786. var indices = [];
  78787. indices.push(0);
  78788. indices.push(1);
  78789. indices.push(2);
  78790. indices.push(0);
  78791. indices.push(2);
  78792. indices.push(3);
  78793. this._indexBuffer = engine.createIndexBuffer(indices);
  78794. };
  78795. Layer.prototype._rebuild = function () {
  78796. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78797. if (vb) {
  78798. vb._rebuild();
  78799. }
  78800. this._createIndexBuffer();
  78801. };
  78802. Layer.prototype.render = function () {
  78803. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  78804. // Check
  78805. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  78806. return;
  78807. var engine = this._scene.getEngine();
  78808. this.onBeforeRenderObservable.notifyObservers(this);
  78809. // Render
  78810. engine.enableEffect(currentEffect);
  78811. engine.setState(false);
  78812. // Texture
  78813. currentEffect.setTexture("textureSampler", this.texture);
  78814. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  78815. // Color
  78816. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  78817. // Scale / offset
  78818. currentEffect.setVector2("offset", this.offset);
  78819. currentEffect.setVector2("scale", this.scale);
  78820. // VBOs
  78821. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  78822. // Draw order
  78823. if (!this.alphaTest) {
  78824. engine.setAlphaMode(this.alphaBlendingMode);
  78825. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78826. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78827. }
  78828. else {
  78829. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78830. }
  78831. this.onAfterRenderObservable.notifyObservers(this);
  78832. };
  78833. Layer.prototype.dispose = function () {
  78834. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78835. if (vertexBuffer) {
  78836. vertexBuffer.dispose();
  78837. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78838. }
  78839. if (this._indexBuffer) {
  78840. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78841. this._indexBuffer = null;
  78842. }
  78843. if (this.texture) {
  78844. this.texture.dispose();
  78845. this.texture = null;
  78846. }
  78847. // Remove from scene
  78848. var index = this._scene.layers.indexOf(this);
  78849. this._scene.layers.splice(index, 1);
  78850. // Callback
  78851. this.onDisposeObservable.notifyObservers(this);
  78852. this.onDisposeObservable.clear();
  78853. this.onAfterRenderObservable.clear();
  78854. this.onBeforeRenderObservable.clear();
  78855. };
  78856. return Layer;
  78857. }());
  78858. BABYLON.Layer = Layer;
  78859. })(BABYLON || (BABYLON = {}));
  78860. //# sourceMappingURL=babylon.layer.js.map
  78861. var BABYLON;
  78862. (function (BABYLON) {
  78863. var TextureTools = /** @class */ (function () {
  78864. function TextureTools() {
  78865. }
  78866. /**
  78867. * Uses the GPU to create a copy texture rescaled at a given size
  78868. * @param texture Texture to copy from
  78869. * @param width Desired width
  78870. * @param height Desired height
  78871. * @return Generated texture
  78872. */
  78873. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  78874. if (useBilinearMode === void 0) { useBilinearMode = true; }
  78875. var scene = texture.getScene();
  78876. var engine = scene.getEngine();
  78877. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  78878. rtt.wrapU = texture.wrapU;
  78879. rtt.wrapV = texture.wrapV;
  78880. rtt.uOffset = texture.uOffset;
  78881. rtt.vOffset = texture.vOffset;
  78882. rtt.uScale = texture.uScale;
  78883. rtt.vScale = texture.vScale;
  78884. rtt.uAng = texture.uAng;
  78885. rtt.vAng = texture.vAng;
  78886. rtt.wAng = texture.wAng;
  78887. rtt.coordinatesIndex = texture.coordinatesIndex;
  78888. rtt.level = texture.level;
  78889. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  78890. rtt._texture.isReady = false;
  78891. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78892. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78893. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78894. passPostProcess.getEffect().executeWhenCompiled(function () {
  78895. passPostProcess.onApply = function (effect) {
  78896. effect.setTexture("textureSampler", texture);
  78897. };
  78898. var internalTexture = rtt.getInternalTexture();
  78899. if (internalTexture) {
  78900. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  78901. engine.unBindFramebuffer(internalTexture);
  78902. rtt.disposeFramebufferObjects();
  78903. passPostProcess.dispose();
  78904. internalTexture.isReady = true;
  78905. }
  78906. });
  78907. return rtt;
  78908. };
  78909. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  78910. if (!scene._environmentBRDFTexture) {
  78911. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78912. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78913. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78914. scene._environmentBRDFTexture = texture;
  78915. }
  78916. return scene._environmentBRDFTexture;
  78917. };
  78918. 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=";
  78919. return TextureTools;
  78920. }());
  78921. BABYLON.TextureTools = TextureTools;
  78922. })(BABYLON || (BABYLON = {}));
  78923. //# sourceMappingURL=babylon.textureTools.js.map
  78924. var BABYLON;
  78925. (function (BABYLON) {
  78926. var FramingBehavior = /** @class */ (function () {
  78927. function FramingBehavior() {
  78928. this._mode = FramingBehavior.FitFrustumSidesMode;
  78929. this._radiusScale = 1.0;
  78930. this._positionScale = 0.5;
  78931. this._defaultElevation = 0.3;
  78932. this._elevationReturnTime = 1500;
  78933. this._elevationReturnWaitTime = 1000;
  78934. this._zoomStopsAnimation = false;
  78935. this._framingTime = 1500;
  78936. this._isPointerDown = false;
  78937. this._lastInteractionTime = -Infinity;
  78938. // Framing control
  78939. this._animatables = new Array();
  78940. this._betaIsAnimating = false;
  78941. }
  78942. Object.defineProperty(FramingBehavior.prototype, "name", {
  78943. get: function () {
  78944. return "Framing";
  78945. },
  78946. enumerable: true,
  78947. configurable: true
  78948. });
  78949. Object.defineProperty(FramingBehavior.prototype, "mode", {
  78950. /**
  78951. * Gets current mode used by the behavior.
  78952. */
  78953. get: function () {
  78954. return this._mode;
  78955. },
  78956. /**
  78957. * Sets the current mode used by the behavior
  78958. */
  78959. set: function (mode) {
  78960. this._mode = mode;
  78961. },
  78962. enumerable: true,
  78963. configurable: true
  78964. });
  78965. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  78966. /**
  78967. * Gets the scale applied to the radius
  78968. */
  78969. get: function () {
  78970. return this._radiusScale;
  78971. },
  78972. /**
  78973. * Sets the scale applied to the radius (1 by default)
  78974. */
  78975. set: function (radius) {
  78976. this._radiusScale = radius;
  78977. },
  78978. enumerable: true,
  78979. configurable: true
  78980. });
  78981. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  78982. /**
  78983. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  78984. */
  78985. get: function () {
  78986. return this._positionScale;
  78987. },
  78988. /**
  78989. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  78990. */
  78991. set: function (scale) {
  78992. this._positionScale = scale;
  78993. },
  78994. enumerable: true,
  78995. configurable: true
  78996. });
  78997. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  78998. /**
  78999. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  79000. * behaviour is triggered, in radians.
  79001. */
  79002. get: function () {
  79003. return this._defaultElevation;
  79004. },
  79005. /**
  79006. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  79007. * behaviour is triggered, in radians.
  79008. */
  79009. set: function (elevation) {
  79010. this._defaultElevation = elevation;
  79011. },
  79012. enumerable: true,
  79013. configurable: true
  79014. });
  79015. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  79016. /**
  79017. * Gets the time (in milliseconds) taken to return to the default beta position.
  79018. * Negative value indicates camera should not return to default.
  79019. */
  79020. get: function () {
  79021. return this._elevationReturnTime;
  79022. },
  79023. /**
  79024. * Sets the time (in milliseconds) taken to return to the default beta position.
  79025. * Negative value indicates camera should not return to default.
  79026. */
  79027. set: function (speed) {
  79028. this._elevationReturnTime = speed;
  79029. },
  79030. enumerable: true,
  79031. configurable: true
  79032. });
  79033. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  79034. /**
  79035. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  79036. */
  79037. get: function () {
  79038. return this._elevationReturnWaitTime;
  79039. },
  79040. /**
  79041. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  79042. */
  79043. set: function (time) {
  79044. this._elevationReturnWaitTime = time;
  79045. },
  79046. enumerable: true,
  79047. configurable: true
  79048. });
  79049. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  79050. /**
  79051. * Gets the flag that indicates if user zooming should stop animation.
  79052. */
  79053. get: function () {
  79054. return this._zoomStopsAnimation;
  79055. },
  79056. /**
  79057. * Sets the flag that indicates if user zooming should stop animation.
  79058. */
  79059. set: function (flag) {
  79060. this._zoomStopsAnimation = flag;
  79061. },
  79062. enumerable: true,
  79063. configurable: true
  79064. });
  79065. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  79066. /**
  79067. * Gets the transition time when framing the mesh, in milliseconds
  79068. */
  79069. get: function () {
  79070. return this._framingTime;
  79071. },
  79072. /**
  79073. * Sets the transition time when framing the mesh, in milliseconds
  79074. */
  79075. set: function (time) {
  79076. this._framingTime = time;
  79077. },
  79078. enumerable: true,
  79079. configurable: true
  79080. });
  79081. FramingBehavior.prototype.init = function () {
  79082. // Do notihng
  79083. };
  79084. FramingBehavior.prototype.attach = function (camera) {
  79085. var _this = this;
  79086. this._attachedCamera = camera;
  79087. var scene = this._attachedCamera.getScene();
  79088. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  79089. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  79090. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  79091. _this._isPointerDown = true;
  79092. return;
  79093. }
  79094. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  79095. _this._isPointerDown = false;
  79096. }
  79097. });
  79098. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  79099. if (mesh) {
  79100. _this.zoomOnMesh(mesh);
  79101. }
  79102. });
  79103. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  79104. // Stop the animation if there is user interaction and the animation should stop for this interaction
  79105. _this._applyUserInteraction();
  79106. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  79107. // back to the default position after a given timeout
  79108. _this._maintainCameraAboveGround();
  79109. });
  79110. };
  79111. FramingBehavior.prototype.detach = function () {
  79112. if (!this._attachedCamera) {
  79113. return;
  79114. }
  79115. var scene = this._attachedCamera.getScene();
  79116. if (this._onPrePointerObservableObserver) {
  79117. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  79118. }
  79119. if (this._onAfterCheckInputsObserver) {
  79120. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  79121. }
  79122. if (this._onMeshTargetChangedObserver) {
  79123. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  79124. }
  79125. this._attachedCamera = null;
  79126. };
  79127. /**
  79128. * Targets the given mesh and updates zoom level accordingly.
  79129. * @param mesh The mesh to target.
  79130. * @param radius Optional. If a cached radius position already exists, overrides default.
  79131. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  79132. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  79133. * @param onAnimationEnd Callback triggered at the end of the framing animation
  79134. */
  79135. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  79136. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  79137. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  79138. mesh.computeWorldMatrix(true);
  79139. var boundingBox = mesh.getBoundingInfo().boundingBox;
  79140. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  79141. };
  79142. /**
  79143. * Targets the given mesh with its children and updates zoom level accordingly.
  79144. * @param mesh The mesh to target.
  79145. * @param radius Optional. If a cached radius position already exists, overrides default.
  79146. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  79147. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  79148. * @param onAnimationEnd Callback triggered at the end of the framing animation
  79149. */
  79150. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  79151. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  79152. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  79153. mesh.computeWorldMatrix(true);
  79154. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  79155. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  79156. };
  79157. /**
  79158. * Targets the given meshes with their children and updates zoom level accordingly.
  79159. * @param meshes The mesh to target.
  79160. * @param radius Optional. If a cached radius position already exists, overrides default.
  79161. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  79162. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  79163. * @param onAnimationEnd Callback triggered at the end of the framing animation
  79164. */
  79165. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  79166. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  79167. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  79168. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  79169. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  79170. for (var i = 0; i < meshes.length; i++) {
  79171. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  79172. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  79173. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  79174. }
  79175. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  79176. };
  79177. /**
  79178. * Targets the given mesh and updates zoom level accordingly.
  79179. * @param mesh The mesh to target.
  79180. * @param radius Optional. If a cached radius position already exists, overrides default.
  79181. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  79182. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  79183. * @param onAnimationEnd Callback triggered at the end of the framing animation
  79184. */
  79185. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  79186. var _this = this;
  79187. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  79188. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  79189. var zoomTarget;
  79190. if (!this._attachedCamera) {
  79191. return;
  79192. }
  79193. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  79194. var bottom = minimumWorld.y;
  79195. var top = maximumWorld.y;
  79196. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  79197. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  79198. if (focusOnOriginXZ) {
  79199. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  79200. }
  79201. else {
  79202. var centerWorld = minimumWorld.add(radiusWorld);
  79203. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  79204. }
  79205. if (!this._vectorTransition) {
  79206. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  79207. }
  79208. this._betaIsAnimating = true;
  79209. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  79210. if (animatable) {
  79211. this._animatables.push(animatable);
  79212. }
  79213. // sets the radius and lower radius bounds
  79214. // Small delta ensures camera is not always at lower zoom limit.
  79215. var radius = 0;
  79216. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  79217. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  79218. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  79219. radius = position;
  79220. }
  79221. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  79222. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  79223. if (this._attachedCamera.lowerRadiusLimit === null) {
  79224. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  79225. }
  79226. }
  79227. // Set sensibilities
  79228. var extend = maximumWorld.subtract(minimumWorld).length();
  79229. this._attachedCamera.panningSensibility = 5000 / extend;
  79230. this._attachedCamera.wheelPrecision = 100 / radius;
  79231. // transition to new radius
  79232. if (!this._radiusTransition) {
  79233. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  79234. }
  79235. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  79236. if (onAnimationEnd) {
  79237. onAnimationEnd();
  79238. }
  79239. if (_this._attachedCamera) {
  79240. _this._attachedCamera.storeState();
  79241. }
  79242. });
  79243. if (animatable) {
  79244. this._animatables.push(animatable);
  79245. }
  79246. };
  79247. /**
  79248. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  79249. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  79250. * frustum width.
  79251. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  79252. * to fully enclose the mesh in the viewing frustum.
  79253. */
  79254. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  79255. var size = maximumWorld.subtract(minimumWorld);
  79256. var boxVectorGlobalDiagonal = size.length();
  79257. var frustumSlope = this._getFrustumSlope();
  79258. // Formula for setting distance
  79259. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  79260. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  79261. // Horizon distance
  79262. var radius = radiusWithoutFraming * this._radiusScale;
  79263. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  79264. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  79265. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  79266. var camera = this._attachedCamera;
  79267. if (!camera) {
  79268. return 0;
  79269. }
  79270. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  79271. // Don't exceed the requested limit
  79272. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  79273. }
  79274. // Don't exceed the upper radius limit
  79275. if (camera.upperRadiusLimit) {
  79276. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  79277. }
  79278. return distance;
  79279. };
  79280. /**
  79281. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  79282. * is automatically returned to its default position (expected to be above ground plane).
  79283. */
  79284. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  79285. var _this = this;
  79286. if (this._elevationReturnTime < 0) {
  79287. return;
  79288. }
  79289. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  79290. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  79291. var limitBeta = Math.PI * 0.5;
  79292. // Bring the camera back up if below the ground plane
  79293. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  79294. this._betaIsAnimating = true;
  79295. //Transition to new position
  79296. this.stopAllAnimations();
  79297. if (!this._betaTransition) {
  79298. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  79299. }
  79300. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  79301. _this._clearAnimationLocks();
  79302. _this.stopAllAnimations();
  79303. });
  79304. if (animatabe) {
  79305. this._animatables.push(animatabe);
  79306. }
  79307. }
  79308. };
  79309. /**
  79310. * Returns the frustum slope based on the canvas ratio and camera FOV
  79311. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  79312. */
  79313. FramingBehavior.prototype._getFrustumSlope = function () {
  79314. // Calculate the viewport ratio
  79315. // Aspect Ratio is Height/Width.
  79316. var camera = this._attachedCamera;
  79317. if (!camera) {
  79318. return BABYLON.Vector2.Zero();
  79319. }
  79320. var engine = camera.getScene().getEngine();
  79321. var aspectRatio = engine.getAspectRatio(camera);
  79322. // Camera FOV is the vertical field of view (top-bottom) in radians.
  79323. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  79324. var frustumSlopeY = Math.tan(camera.fov / 2);
  79325. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  79326. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  79327. // along the forward vector.
  79328. var frustumSlopeX = frustumSlopeY * aspectRatio;
  79329. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  79330. };
  79331. /**
  79332. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  79333. */
  79334. FramingBehavior.prototype._clearAnimationLocks = function () {
  79335. this._betaIsAnimating = false;
  79336. };
  79337. /**
  79338. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  79339. */
  79340. FramingBehavior.prototype._applyUserInteraction = function () {
  79341. if (this.isUserIsMoving) {
  79342. this._lastInteractionTime = BABYLON.Tools.Now;
  79343. this.stopAllAnimations();
  79344. this._clearAnimationLocks();
  79345. }
  79346. };
  79347. /**
  79348. * Stops and removes all animations that have been applied to the camera
  79349. */
  79350. FramingBehavior.prototype.stopAllAnimations = function () {
  79351. if (this._attachedCamera) {
  79352. this._attachedCamera.animations = [];
  79353. }
  79354. while (this._animatables.length) {
  79355. if (this._animatables[0]) {
  79356. this._animatables[0].onAnimationEnd = null;
  79357. this._animatables[0].stop();
  79358. }
  79359. this._animatables.shift();
  79360. }
  79361. };
  79362. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  79363. /**
  79364. * Gets a value indicating if the user is moving the camera
  79365. */
  79366. get: function () {
  79367. if (!this._attachedCamera) {
  79368. return false;
  79369. }
  79370. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  79371. this._attachedCamera.inertialBetaOffset !== 0 ||
  79372. this._attachedCamera.inertialRadiusOffset !== 0 ||
  79373. this._attachedCamera.inertialPanningX !== 0 ||
  79374. this._attachedCamera.inertialPanningY !== 0 ||
  79375. this._isPointerDown;
  79376. },
  79377. enumerable: true,
  79378. configurable: true
  79379. });
  79380. /**
  79381. * The easing function used by animations
  79382. */
  79383. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  79384. /**
  79385. * The easing mode used by animations
  79386. */
  79387. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  79388. // Statics
  79389. /**
  79390. * The camera can move all the way towards the mesh.
  79391. */
  79392. FramingBehavior.IgnoreBoundsSizeMode = 0;
  79393. /**
  79394. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  79395. */
  79396. FramingBehavior.FitFrustumSidesMode = 1;
  79397. return FramingBehavior;
  79398. }());
  79399. BABYLON.FramingBehavior = FramingBehavior;
  79400. })(BABYLON || (BABYLON = {}));
  79401. //# sourceMappingURL=babylon.framingBehavior.js.map
  79402. var BABYLON;
  79403. (function (BABYLON) {
  79404. /**
  79405. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  79406. */
  79407. var BouncingBehavior = /** @class */ (function () {
  79408. function BouncingBehavior() {
  79409. /**
  79410. * The duration of the animation, in milliseconds
  79411. */
  79412. this.transitionDuration = 450;
  79413. /**
  79414. * Length of the distance animated by the transition when lower radius is reached
  79415. */
  79416. this.lowerRadiusTransitionRange = 2;
  79417. /**
  79418. * Length of the distance animated by the transition when upper radius is reached
  79419. */
  79420. this.upperRadiusTransitionRange = -2;
  79421. this._autoTransitionRange = false;
  79422. // Animations
  79423. this._radiusIsAnimating = false;
  79424. this._radiusBounceTransition = null;
  79425. this._animatables = new Array();
  79426. }
  79427. Object.defineProperty(BouncingBehavior.prototype, "name", {
  79428. get: function () {
  79429. return "Bouncing";
  79430. },
  79431. enumerable: true,
  79432. configurable: true
  79433. });
  79434. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  79435. /**
  79436. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  79437. */
  79438. get: function () {
  79439. return this._autoTransitionRange;
  79440. },
  79441. /**
  79442. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  79443. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  79444. */
  79445. set: function (value) {
  79446. var _this = this;
  79447. if (this._autoTransitionRange === value) {
  79448. return;
  79449. }
  79450. this._autoTransitionRange = value;
  79451. var camera = this._attachedCamera;
  79452. if (!camera) {
  79453. return;
  79454. }
  79455. if (value) {
  79456. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  79457. if (!mesh) {
  79458. return;
  79459. }
  79460. mesh.computeWorldMatrix(true);
  79461. var diagonal = mesh.getBoundingInfo().diagonalLength;
  79462. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  79463. _this.upperRadiusTransitionRange = diagonal * 0.05;
  79464. });
  79465. }
  79466. else if (this._onMeshTargetChangedObserver) {
  79467. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  79468. }
  79469. },
  79470. enumerable: true,
  79471. configurable: true
  79472. });
  79473. BouncingBehavior.prototype.init = function () {
  79474. // Do notihng
  79475. };
  79476. BouncingBehavior.prototype.attach = function (camera) {
  79477. var _this = this;
  79478. this._attachedCamera = camera;
  79479. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  79480. if (!_this._attachedCamera) {
  79481. return;
  79482. }
  79483. // Add the bounce animation to the lower radius limit
  79484. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  79485. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  79486. }
  79487. // Add the bounce animation to the upper radius limit
  79488. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  79489. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  79490. }
  79491. });
  79492. };
  79493. BouncingBehavior.prototype.detach = function () {
  79494. if (!this._attachedCamera) {
  79495. return;
  79496. }
  79497. if (this._onAfterCheckInputsObserver) {
  79498. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  79499. }
  79500. if (this._onMeshTargetChangedObserver) {
  79501. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  79502. }
  79503. this._attachedCamera = null;
  79504. };
  79505. /**
  79506. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  79507. * @param radiusLimit The limit to check against.
  79508. * @return Bool to indicate if at limit.
  79509. */
  79510. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  79511. if (!this._attachedCamera) {
  79512. return false;
  79513. }
  79514. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  79515. return true;
  79516. }
  79517. return false;
  79518. };
  79519. /**
  79520. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  79521. * @param radiusDelta The delta by which to animate to. Can be negative.
  79522. */
  79523. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  79524. var _this = this;
  79525. if (!this._attachedCamera) {
  79526. return;
  79527. }
  79528. if (!this._radiusBounceTransition) {
  79529. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  79530. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  79531. }
  79532. // Prevent zoom until bounce has completed
  79533. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  79534. this._attachedCamera.wheelPrecision = Infinity;
  79535. this._attachedCamera.inertialRadiusOffset = 0;
  79536. // Animate to the radius limit
  79537. this.stopAllAnimations();
  79538. this._radiusIsAnimating = true;
  79539. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  79540. if (animatable) {
  79541. this._animatables.push(animatable);
  79542. }
  79543. };
  79544. /**
  79545. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  79546. */
  79547. BouncingBehavior.prototype._clearAnimationLocks = function () {
  79548. this._radiusIsAnimating = false;
  79549. if (this._attachedCamera) {
  79550. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  79551. }
  79552. };
  79553. /**
  79554. * Stops and removes all animations that have been applied to the camera
  79555. */
  79556. BouncingBehavior.prototype.stopAllAnimations = function () {
  79557. if (this._attachedCamera) {
  79558. this._attachedCamera.animations = [];
  79559. }
  79560. while (this._animatables.length) {
  79561. this._animatables[0].onAnimationEnd = null;
  79562. this._animatables[0].stop();
  79563. this._animatables.shift();
  79564. }
  79565. };
  79566. /**
  79567. * The easing function used by animations
  79568. */
  79569. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  79570. /**
  79571. * The easing mode used by animations
  79572. */
  79573. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  79574. return BouncingBehavior;
  79575. }());
  79576. BABYLON.BouncingBehavior = BouncingBehavior;
  79577. })(BABYLON || (BABYLON = {}));
  79578. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  79579. var BABYLON;
  79580. (function (BABYLON) {
  79581. var AutoRotationBehavior = /** @class */ (function () {
  79582. function AutoRotationBehavior() {
  79583. this._zoomStopsAnimation = false;
  79584. this._idleRotationSpeed = 0.05;
  79585. this._idleRotationWaitTime = 2000;
  79586. this._idleRotationSpinupTime = 2000;
  79587. this._isPointerDown = false;
  79588. this._lastFrameTime = null;
  79589. this._lastInteractionTime = -Infinity;
  79590. this._cameraRotationSpeed = 0;
  79591. this._lastFrameRadius = 0;
  79592. }
  79593. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  79594. get: function () {
  79595. return "AutoRotation";
  79596. },
  79597. enumerable: true,
  79598. configurable: true
  79599. });
  79600. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  79601. /**
  79602. * Gets the flag that indicates if user zooming should stop animation.
  79603. */
  79604. get: function () {
  79605. return this._zoomStopsAnimation;
  79606. },
  79607. /**
  79608. * Sets the flag that indicates if user zooming should stop animation.
  79609. */
  79610. set: function (flag) {
  79611. this._zoomStopsAnimation = flag;
  79612. },
  79613. enumerable: true,
  79614. configurable: true
  79615. });
  79616. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  79617. /**
  79618. * Gets the default speed at which the camera rotates around the model.
  79619. */
  79620. get: function () {
  79621. return this._idleRotationSpeed;
  79622. },
  79623. /**
  79624. * Sets the default speed at which the camera rotates around the model.
  79625. */
  79626. set: function (speed) {
  79627. this._idleRotationSpeed = speed;
  79628. },
  79629. enumerable: true,
  79630. configurable: true
  79631. });
  79632. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  79633. /**
  79634. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  79635. */
  79636. get: function () {
  79637. return this._idleRotationWaitTime;
  79638. },
  79639. /**
  79640. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  79641. */
  79642. set: function (time) {
  79643. this._idleRotationWaitTime = time;
  79644. },
  79645. enumerable: true,
  79646. configurable: true
  79647. });
  79648. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  79649. /**
  79650. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  79651. */
  79652. get: function () {
  79653. return this._idleRotationSpinupTime;
  79654. },
  79655. /**
  79656. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  79657. */
  79658. set: function (time) {
  79659. this._idleRotationSpinupTime = time;
  79660. },
  79661. enumerable: true,
  79662. configurable: true
  79663. });
  79664. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  79665. /**
  79666. * Gets a value indicating if the camera is currently rotating because of this behavior
  79667. */
  79668. get: function () {
  79669. return Math.abs(this._cameraRotationSpeed) > 0;
  79670. },
  79671. enumerable: true,
  79672. configurable: true
  79673. });
  79674. AutoRotationBehavior.prototype.init = function () {
  79675. // Do notihng
  79676. };
  79677. AutoRotationBehavior.prototype.attach = function (camera) {
  79678. var _this = this;
  79679. this._attachedCamera = camera;
  79680. var scene = this._attachedCamera.getScene();
  79681. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  79682. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  79683. _this._isPointerDown = true;
  79684. return;
  79685. }
  79686. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  79687. _this._isPointerDown = false;
  79688. }
  79689. });
  79690. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  79691. var now = BABYLON.Tools.Now;
  79692. var dt = 0;
  79693. if (_this._lastFrameTime != null) {
  79694. dt = now - _this._lastFrameTime;
  79695. }
  79696. _this._lastFrameTime = now;
  79697. // Stop the animation if there is user interaction and the animation should stop for this interaction
  79698. _this._applyUserInteraction();
  79699. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  79700. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  79701. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  79702. // Step camera rotation by rotation speed
  79703. if (_this._attachedCamera) {
  79704. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  79705. }
  79706. });
  79707. };
  79708. AutoRotationBehavior.prototype.detach = function () {
  79709. if (!this._attachedCamera) {
  79710. return;
  79711. }
  79712. var scene = this._attachedCamera.getScene();
  79713. if (this._onPrePointerObservableObserver) {
  79714. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  79715. }
  79716. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  79717. this._attachedCamera = null;
  79718. };
  79719. /**
  79720. * Returns true if user is scrolling.
  79721. * @return true if user is scrolling.
  79722. */
  79723. AutoRotationBehavior.prototype._userIsZooming = function () {
  79724. if (!this._attachedCamera) {
  79725. return false;
  79726. }
  79727. return this._attachedCamera.inertialRadiusOffset !== 0;
  79728. };
  79729. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  79730. if (!this._attachedCamera) {
  79731. return false;
  79732. }
  79733. var zoomHasHitLimit = false;
  79734. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  79735. zoomHasHitLimit = true;
  79736. }
  79737. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  79738. this._lastFrameRadius = this._attachedCamera.radius;
  79739. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  79740. };
  79741. /**
  79742. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  79743. */
  79744. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  79745. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  79746. this._lastInteractionTime = BABYLON.Tools.Now;
  79747. }
  79748. };
  79749. // Tools
  79750. AutoRotationBehavior.prototype._userIsMoving = function () {
  79751. if (!this._attachedCamera) {
  79752. return false;
  79753. }
  79754. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  79755. this._attachedCamera.inertialBetaOffset !== 0 ||
  79756. this._attachedCamera.inertialRadiusOffset !== 0 ||
  79757. this._attachedCamera.inertialPanningX !== 0 ||
  79758. this._attachedCamera.inertialPanningY !== 0 ||
  79759. this._isPointerDown;
  79760. };
  79761. return AutoRotationBehavior;
  79762. }());
  79763. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  79764. })(BABYLON || (BABYLON = {}));
  79765. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  79766. var BABYLON;
  79767. (function (BABYLON) {
  79768. var NullEngineOptions = /** @class */ (function () {
  79769. function NullEngineOptions() {
  79770. this.renderWidth = 512;
  79771. this.renderHeight = 256;
  79772. this.textureSize = 512;
  79773. this.deterministicLockstep = false;
  79774. this.lockstepMaxSteps = 4;
  79775. }
  79776. return NullEngineOptions;
  79777. }());
  79778. BABYLON.NullEngineOptions = NullEngineOptions;
  79779. /**
  79780. * The null engine class provides support for headless version of babylon.js.
  79781. * This can be used in server side scenario or for testing purposes
  79782. */
  79783. var NullEngine = /** @class */ (function (_super) {
  79784. __extends(NullEngine, _super);
  79785. function NullEngine(options) {
  79786. if (options === void 0) { options = new NullEngineOptions(); }
  79787. var _this = _super.call(this, null) || this;
  79788. if (options.deterministicLockstep === undefined) {
  79789. options.deterministicLockstep = false;
  79790. }
  79791. if (options.lockstepMaxSteps === undefined) {
  79792. options.lockstepMaxSteps = 4;
  79793. }
  79794. _this._options = options;
  79795. // Init caps
  79796. // We consider we are on a webgl1 capable device
  79797. _this._caps = new BABYLON.EngineCapabilities();
  79798. _this._caps.maxTexturesImageUnits = 16;
  79799. _this._caps.maxVertexTextureImageUnits = 16;
  79800. _this._caps.maxTextureSize = 512;
  79801. _this._caps.maxCubemapTextureSize = 512;
  79802. _this._caps.maxRenderTextureSize = 512;
  79803. _this._caps.maxVertexAttribs = 16;
  79804. _this._caps.maxVaryingVectors = 16;
  79805. _this._caps.maxFragmentUniformVectors = 16;
  79806. _this._caps.maxVertexUniformVectors = 16;
  79807. // Extensions
  79808. _this._caps.standardDerivatives = false;
  79809. _this._caps.astc = null;
  79810. _this._caps.s3tc = null;
  79811. _this._caps.pvrtc = null;
  79812. _this._caps.etc1 = null;
  79813. _this._caps.etc2 = null;
  79814. _this._caps.textureAnisotropicFilterExtension = null;
  79815. _this._caps.maxAnisotropy = 0;
  79816. _this._caps.uintIndices = false;
  79817. _this._caps.fragmentDepthSupported = false;
  79818. _this._caps.highPrecisionShaderSupported = true;
  79819. _this._caps.colorBufferFloat = false;
  79820. _this._caps.textureFloat = false;
  79821. _this._caps.textureFloatLinearFiltering = false;
  79822. _this._caps.textureFloatRender = false;
  79823. _this._caps.textureHalfFloat = false;
  79824. _this._caps.textureHalfFloatLinearFiltering = false;
  79825. _this._caps.textureHalfFloatRender = false;
  79826. _this._caps.textureLOD = false;
  79827. _this._caps.drawBuffersExtension = false;
  79828. _this._caps.depthTextureExtension = false;
  79829. _this._caps.vertexArrayObject = false;
  79830. _this._caps.instancedArrays = false;
  79831. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  79832. // Wrappers
  79833. if (typeof URL === "undefined") {
  79834. URL = {
  79835. createObjectURL: function () { },
  79836. revokeObjectURL: function () { }
  79837. };
  79838. }
  79839. if (typeof Blob === "undefined") {
  79840. Blob = function () { };
  79841. }
  79842. return _this;
  79843. }
  79844. NullEngine.prototype.isDeterministicLockStep = function () {
  79845. return this._options.deterministicLockstep;
  79846. };
  79847. NullEngine.prototype.getLockstepMaxSteps = function () {
  79848. return this._options.lockstepMaxSteps;
  79849. };
  79850. NullEngine.prototype.createVertexBuffer = function (vertices) {
  79851. return {
  79852. capacity: 0,
  79853. references: 1,
  79854. is32Bits: false
  79855. };
  79856. };
  79857. NullEngine.prototype.createIndexBuffer = function (indices) {
  79858. return {
  79859. capacity: 0,
  79860. references: 1,
  79861. is32Bits: false
  79862. };
  79863. };
  79864. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  79865. if (stencil === void 0) { stencil = false; }
  79866. };
  79867. NullEngine.prototype.getRenderWidth = function (useScreen) {
  79868. if (useScreen === void 0) { useScreen = false; }
  79869. if (!useScreen && this._currentRenderTarget) {
  79870. return this._currentRenderTarget.width;
  79871. }
  79872. return this._options.renderWidth;
  79873. };
  79874. NullEngine.prototype.getRenderHeight = function (useScreen) {
  79875. if (useScreen === void 0) { useScreen = false; }
  79876. if (!useScreen && this._currentRenderTarget) {
  79877. return this._currentRenderTarget.height;
  79878. }
  79879. return this._options.renderHeight;
  79880. };
  79881. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  79882. this._cachedViewport = viewport;
  79883. };
  79884. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  79885. return {
  79886. transformFeedback: null,
  79887. __SPECTOR_rebuildProgram: null
  79888. };
  79889. };
  79890. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  79891. return [];
  79892. };
  79893. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  79894. return [];
  79895. };
  79896. NullEngine.prototype.bindSamplers = function (effect) {
  79897. this._currentEffect = null;
  79898. };
  79899. NullEngine.prototype.enableEffect = function (effect) {
  79900. this._currentEffect = effect;
  79901. if (effect.onBind) {
  79902. effect.onBind(effect);
  79903. }
  79904. effect.onBindObservable.notifyObservers(effect);
  79905. };
  79906. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  79907. if (zOffset === void 0) { zOffset = 0; }
  79908. if (reverseSide === void 0) { reverseSide = false; }
  79909. };
  79910. NullEngine.prototype.setIntArray = function (uniform, array) {
  79911. };
  79912. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  79913. };
  79914. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  79915. };
  79916. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  79917. };
  79918. NullEngine.prototype.setFloatArray = function (uniform, array) {
  79919. };
  79920. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  79921. };
  79922. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  79923. };
  79924. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  79925. };
  79926. NullEngine.prototype.setArray = function (uniform, array) {
  79927. };
  79928. NullEngine.prototype.setArray2 = function (uniform, array) {
  79929. };
  79930. NullEngine.prototype.setArray3 = function (uniform, array) {
  79931. };
  79932. NullEngine.prototype.setArray4 = function (uniform, array) {
  79933. };
  79934. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  79935. };
  79936. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  79937. };
  79938. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  79939. };
  79940. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  79941. };
  79942. NullEngine.prototype.setFloat = function (uniform, value) {
  79943. };
  79944. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  79945. };
  79946. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  79947. };
  79948. NullEngine.prototype.setBool = function (uniform, bool) {
  79949. };
  79950. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  79951. };
  79952. NullEngine.prototype.setColor3 = function (uniform, color3) {
  79953. };
  79954. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  79955. };
  79956. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  79957. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  79958. if (this._alphaMode === mode) {
  79959. return;
  79960. }
  79961. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  79962. if (!noDepthWriteChange) {
  79963. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  79964. }
  79965. this._alphaMode = mode;
  79966. };
  79967. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  79968. };
  79969. NullEngine.prototype.wipeCaches = function (bruteForce) {
  79970. if (this.preventCacheWipeBetweenFrames) {
  79971. return;
  79972. }
  79973. this.resetTextureCache();
  79974. this._currentEffect = null;
  79975. if (bruteForce) {
  79976. this._currentProgram = null;
  79977. this._stencilState.reset();
  79978. this._depthCullingState.reset();
  79979. this.setDepthFunctionToLessOrEqual();
  79980. this._alphaState.reset();
  79981. }
  79982. this._cachedVertexBuffers = null;
  79983. this._cachedIndexBuffer = null;
  79984. this._cachedEffectForVertexBuffers = null;
  79985. };
  79986. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  79987. };
  79988. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  79989. };
  79990. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  79991. };
  79992. NullEngine.prototype._createTexture = function () {
  79993. return {};
  79994. };
  79995. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  79996. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  79997. if (onLoad === void 0) { onLoad = null; }
  79998. if (onError === void 0) { onError = null; }
  79999. if (buffer === void 0) { buffer = null; }
  80000. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  80001. var url = String(urlArg);
  80002. texture.url = url;
  80003. texture.generateMipMaps = !noMipmap;
  80004. texture.samplingMode = samplingMode;
  80005. texture.invertY = invertY;
  80006. texture.baseWidth = this._options.textureSize;
  80007. texture.baseHeight = this._options.textureSize;
  80008. texture.width = this._options.textureSize;
  80009. texture.height = this._options.textureSize;
  80010. if (format) {
  80011. texture.format = format;
  80012. }
  80013. texture.isReady = true;
  80014. if (onLoad) {
  80015. onLoad();
  80016. }
  80017. return texture;
  80018. };
  80019. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  80020. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  80021. if (options !== undefined && typeof options === "object") {
  80022. fullOptions.generateMipMaps = options.generateMipMaps;
  80023. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  80024. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  80025. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  80026. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  80027. }
  80028. else {
  80029. fullOptions.generateMipMaps = options;
  80030. fullOptions.generateDepthBuffer = true;
  80031. fullOptions.generateStencilBuffer = false;
  80032. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80033. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  80034. }
  80035. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  80036. var width = size.width || size;
  80037. var height = size.height || size;
  80038. texture._depthStencilBuffer = {};
  80039. texture._framebuffer = {};
  80040. texture.baseWidth = width;
  80041. texture.baseHeight = height;
  80042. texture.width = width;
  80043. texture.height = height;
  80044. texture.isReady = true;
  80045. texture.samples = 1;
  80046. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  80047. texture.samplingMode = fullOptions.samplingMode;
  80048. texture.type = fullOptions.type;
  80049. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  80050. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  80051. return texture;
  80052. };
  80053. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  80054. texture.samplingMode = samplingMode;
  80055. };
  80056. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  80057. if (this._currentRenderTarget) {
  80058. this.unBindFramebuffer(this._currentRenderTarget);
  80059. }
  80060. this._currentRenderTarget = texture;
  80061. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  80062. if (this._cachedViewport && !forceFullscreenViewport) {
  80063. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  80064. }
  80065. };
  80066. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  80067. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  80068. this._currentRenderTarget = null;
  80069. if (onBeforeUnbind) {
  80070. if (texture._MSAAFramebuffer) {
  80071. this._currentFramebuffer = texture._framebuffer;
  80072. }
  80073. onBeforeUnbind();
  80074. }
  80075. this._currentFramebuffer = null;
  80076. };
  80077. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  80078. var vbo = {
  80079. capacity: 1,
  80080. references: 1,
  80081. is32Bits: false
  80082. };
  80083. return vbo;
  80084. };
  80085. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  80086. if (offset === void 0) { offset = 0; }
  80087. };
  80088. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  80089. };
  80090. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  80091. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  80092. this._boundTexturesCache[this._activeChannel] = texture;
  80093. }
  80094. };
  80095. NullEngine.prototype._bindTexture = function (channel, texture) {
  80096. if (channel < 0) {
  80097. return;
  80098. }
  80099. this._bindTextureDirectly(0, texture);
  80100. };
  80101. NullEngine.prototype._releaseBuffer = function (buffer) {
  80102. buffer.references--;
  80103. if (buffer.references === 0) {
  80104. return true;
  80105. }
  80106. return false;
  80107. };
  80108. return NullEngine;
  80109. }(BABYLON.Engine));
  80110. BABYLON.NullEngine = NullEngine;
  80111. })(BABYLON || (BABYLON = {}));
  80112. //# sourceMappingURL=babylon.nullEngine.js.map
  80113. var BABYLON;
  80114. (function (BABYLON) {
  80115. /**
  80116. * This class can be used to get instrumentation data from a Babylon engine
  80117. */
  80118. var EngineInstrumentation = /** @class */ (function () {
  80119. function EngineInstrumentation(engine) {
  80120. this.engine = engine;
  80121. this._captureGPUFrameTime = false;
  80122. this._gpuFrameTime = new BABYLON.PerfCounter();
  80123. this._captureShaderCompilationTime = false;
  80124. this._shaderCompilationTime = new BABYLON.PerfCounter();
  80125. // Observers
  80126. this._onBeginFrameObserver = null;
  80127. this._onEndFrameObserver = null;
  80128. this._onBeforeShaderCompilationObserver = null;
  80129. this._onAfterShaderCompilationObserver = null;
  80130. }
  80131. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  80132. // Properties
  80133. /**
  80134. * Gets the perf counter used for GPU frame time
  80135. */
  80136. get: function () {
  80137. return this._gpuFrameTime;
  80138. },
  80139. enumerable: true,
  80140. configurable: true
  80141. });
  80142. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  80143. /**
  80144. * Gets the GPU frame time capture status
  80145. */
  80146. get: function () {
  80147. return this._captureGPUFrameTime;
  80148. },
  80149. /**
  80150. * Enable or disable the GPU frame time capture
  80151. */
  80152. set: function (value) {
  80153. var _this = this;
  80154. if (value === this._captureGPUFrameTime) {
  80155. return;
  80156. }
  80157. this._captureGPUFrameTime = value;
  80158. if (value) {
  80159. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  80160. if (!_this._gpuFrameTimeToken) {
  80161. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  80162. }
  80163. });
  80164. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  80165. if (!_this._gpuFrameTimeToken) {
  80166. return;
  80167. }
  80168. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  80169. if (time > -1) {
  80170. _this._gpuFrameTimeToken = null;
  80171. _this._gpuFrameTime.fetchNewFrame();
  80172. _this._gpuFrameTime.addCount(time, true);
  80173. }
  80174. });
  80175. }
  80176. else {
  80177. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  80178. this._onBeginFrameObserver = null;
  80179. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  80180. this._onEndFrameObserver = null;
  80181. }
  80182. },
  80183. enumerable: true,
  80184. configurable: true
  80185. });
  80186. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  80187. /**
  80188. * Gets the perf counter used for shader compilation time
  80189. */
  80190. get: function () {
  80191. return this._shaderCompilationTime;
  80192. },
  80193. enumerable: true,
  80194. configurable: true
  80195. });
  80196. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  80197. /**
  80198. * Gets the shader compilation time capture status
  80199. */
  80200. get: function () {
  80201. return this._captureShaderCompilationTime;
  80202. },
  80203. /**
  80204. * Enable or disable the shader compilation time capture
  80205. */
  80206. set: function (value) {
  80207. var _this = this;
  80208. if (value === this._captureShaderCompilationTime) {
  80209. return;
  80210. }
  80211. this._captureShaderCompilationTime = value;
  80212. if (value) {
  80213. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  80214. _this._shaderCompilationTime.fetchNewFrame();
  80215. _this._shaderCompilationTime.beginMonitoring();
  80216. });
  80217. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  80218. _this._shaderCompilationTime.endMonitoring();
  80219. });
  80220. }
  80221. else {
  80222. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  80223. this._onBeforeShaderCompilationObserver = null;
  80224. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  80225. this._onAfterShaderCompilationObserver = null;
  80226. }
  80227. },
  80228. enumerable: true,
  80229. configurable: true
  80230. });
  80231. EngineInstrumentation.prototype.dispose = function () {
  80232. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  80233. this._onBeginFrameObserver = null;
  80234. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  80235. this._onEndFrameObserver = null;
  80236. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  80237. this._onBeforeShaderCompilationObserver = null;
  80238. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  80239. this._onAfterShaderCompilationObserver = null;
  80240. this.engine = null;
  80241. };
  80242. return EngineInstrumentation;
  80243. }());
  80244. BABYLON.EngineInstrumentation = EngineInstrumentation;
  80245. })(BABYLON || (BABYLON = {}));
  80246. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  80247. var BABYLON;
  80248. (function (BABYLON) {
  80249. /**
  80250. * This class can be used to get instrumentation data from a Babylon engine
  80251. */
  80252. var SceneInstrumentation = /** @class */ (function () {
  80253. function SceneInstrumentation(scene) {
  80254. var _this = this;
  80255. this.scene = scene;
  80256. this._captureActiveMeshesEvaluationTime = false;
  80257. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  80258. this._captureRenderTargetsRenderTime = false;
  80259. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  80260. this._captureFrameTime = false;
  80261. this._frameTime = new BABYLON.PerfCounter();
  80262. this._captureRenderTime = false;
  80263. this._renderTime = new BABYLON.PerfCounter();
  80264. this._captureInterFrameTime = false;
  80265. this._interFrameTime = new BABYLON.PerfCounter();
  80266. this._captureParticlesRenderTime = false;
  80267. this._particlesRenderTime = new BABYLON.PerfCounter();
  80268. this._captureSpritesRenderTime = false;
  80269. this._spritesRenderTime = new BABYLON.PerfCounter();
  80270. this._capturePhysicsTime = false;
  80271. this._physicsTime = new BABYLON.PerfCounter();
  80272. this._captureAnimationsTime = false;
  80273. this._animationsTime = new BABYLON.PerfCounter();
  80274. // Observers
  80275. this._onBeforeActiveMeshesEvaluationObserver = null;
  80276. this._onAfterActiveMeshesEvaluationObserver = null;
  80277. this._onBeforeRenderTargetsRenderObserver = null;
  80278. this._onAfterRenderTargetsRenderObserver = null;
  80279. this._onAfterRenderObserver = null;
  80280. this._onBeforeDrawPhaseObserver = null;
  80281. this._onAfterDrawPhaseObserver = null;
  80282. this._onBeforeAnimationsObserver = null;
  80283. this._onBeforeParticlesRenderingObserver = null;
  80284. this._onAfterParticlesRenderingObserver = null;
  80285. this._onBeforeSpritesRenderingObserver = null;
  80286. this._onAfterSpritesRenderingObserver = null;
  80287. this._onBeforePhysicsObserver = null;
  80288. this._onAfterPhysicsObserver = null;
  80289. this._onAfterAnimationsObserver = null;
  80290. // Before render
  80291. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  80292. if (_this._captureActiveMeshesEvaluationTime) {
  80293. _this._activeMeshesEvaluationTime.fetchNewFrame();
  80294. }
  80295. if (_this._captureRenderTargetsRenderTime) {
  80296. _this._renderTargetsRenderTime.fetchNewFrame();
  80297. }
  80298. if (_this._captureFrameTime) {
  80299. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  80300. _this._frameTime.beginMonitoring();
  80301. }
  80302. if (_this._captureInterFrameTime) {
  80303. _this._interFrameTime.endMonitoring();
  80304. }
  80305. if (_this._captureParticlesRenderTime) {
  80306. _this._particlesRenderTime.fetchNewFrame();
  80307. }
  80308. if (_this._captureSpritesRenderTime) {
  80309. _this._spritesRenderTime.fetchNewFrame();
  80310. }
  80311. if (_this._captureAnimationsTime) {
  80312. _this._animationsTime.beginMonitoring();
  80313. }
  80314. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  80315. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  80316. });
  80317. // After render
  80318. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  80319. if (_this._captureFrameTime) {
  80320. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  80321. _this._frameTime.endMonitoring();
  80322. }
  80323. if (_this._captureRenderTime) {
  80324. _this._renderTime.endMonitoring(false);
  80325. }
  80326. if (_this._captureInterFrameTime) {
  80327. _this._interFrameTime.beginMonitoring();
  80328. }
  80329. });
  80330. }
  80331. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  80332. // Properties
  80333. /**
  80334. * Gets the perf counter used for active meshes evaluation time
  80335. */
  80336. get: function () {
  80337. return this._activeMeshesEvaluationTime;
  80338. },
  80339. enumerable: true,
  80340. configurable: true
  80341. });
  80342. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  80343. /**
  80344. * Gets the active meshes evaluation time capture status
  80345. */
  80346. get: function () {
  80347. return this._captureActiveMeshesEvaluationTime;
  80348. },
  80349. /**
  80350. * Enable or disable the active meshes evaluation time capture
  80351. */
  80352. set: function (value) {
  80353. var _this = this;
  80354. if (value === this._captureActiveMeshesEvaluationTime) {
  80355. return;
  80356. }
  80357. this._captureActiveMeshesEvaluationTime = value;
  80358. if (value) {
  80359. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  80360. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  80361. _this._activeMeshesEvaluationTime.beginMonitoring();
  80362. });
  80363. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  80364. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  80365. _this._activeMeshesEvaluationTime.endMonitoring();
  80366. });
  80367. }
  80368. else {
  80369. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  80370. this._onBeforeActiveMeshesEvaluationObserver = null;
  80371. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  80372. this._onAfterActiveMeshesEvaluationObserver = null;
  80373. }
  80374. },
  80375. enumerable: true,
  80376. configurable: true
  80377. });
  80378. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  80379. /**
  80380. * Gets the perf counter used for render targets render time
  80381. */
  80382. get: function () {
  80383. return this._renderTargetsRenderTime;
  80384. },
  80385. enumerable: true,
  80386. configurable: true
  80387. });
  80388. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  80389. /**
  80390. * Gets the render targets render time capture status
  80391. */
  80392. get: function () {
  80393. return this._captureRenderTargetsRenderTime;
  80394. },
  80395. /**
  80396. * Enable or disable the render targets render time capture
  80397. */
  80398. set: function (value) {
  80399. var _this = this;
  80400. if (value === this._captureRenderTargetsRenderTime) {
  80401. return;
  80402. }
  80403. this._captureRenderTargetsRenderTime = value;
  80404. if (value) {
  80405. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  80406. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  80407. _this._renderTargetsRenderTime.beginMonitoring();
  80408. });
  80409. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  80410. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  80411. _this._renderTargetsRenderTime.endMonitoring(false);
  80412. });
  80413. }
  80414. else {
  80415. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  80416. this._onBeforeRenderTargetsRenderObserver = null;
  80417. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  80418. this._onAfterRenderTargetsRenderObserver = null;
  80419. }
  80420. },
  80421. enumerable: true,
  80422. configurable: true
  80423. });
  80424. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  80425. /**
  80426. * Gets the perf counter used for particles render time
  80427. */
  80428. get: function () {
  80429. return this._particlesRenderTime;
  80430. },
  80431. enumerable: true,
  80432. configurable: true
  80433. });
  80434. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  80435. /**
  80436. * Gets the particles render time capture status
  80437. */
  80438. get: function () {
  80439. return this._captureParticlesRenderTime;
  80440. },
  80441. /**
  80442. * Enable or disable the particles render time capture
  80443. */
  80444. set: function (value) {
  80445. var _this = this;
  80446. if (value === this._captureParticlesRenderTime) {
  80447. return;
  80448. }
  80449. this._captureParticlesRenderTime = value;
  80450. if (value) {
  80451. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  80452. BABYLON.Tools.StartPerformanceCounter("Particles");
  80453. _this._particlesRenderTime.beginMonitoring();
  80454. });
  80455. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  80456. BABYLON.Tools.EndPerformanceCounter("Particles");
  80457. _this._particlesRenderTime.endMonitoring(false);
  80458. });
  80459. }
  80460. else {
  80461. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  80462. this._onBeforeParticlesRenderingObserver = null;
  80463. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  80464. this._onAfterParticlesRenderingObserver = null;
  80465. }
  80466. },
  80467. enumerable: true,
  80468. configurable: true
  80469. });
  80470. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  80471. /**
  80472. * Gets the perf counter used for sprites render time
  80473. */
  80474. get: function () {
  80475. return this._spritesRenderTime;
  80476. },
  80477. enumerable: true,
  80478. configurable: true
  80479. });
  80480. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  80481. /**
  80482. * Gets the sprites render time capture status
  80483. */
  80484. get: function () {
  80485. return this._captureSpritesRenderTime;
  80486. },
  80487. /**
  80488. * Enable or disable the sprites render time capture
  80489. */
  80490. set: function (value) {
  80491. var _this = this;
  80492. if (value === this._captureSpritesRenderTime) {
  80493. return;
  80494. }
  80495. this._captureSpritesRenderTime = value;
  80496. if (value) {
  80497. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  80498. BABYLON.Tools.StartPerformanceCounter("Sprites");
  80499. _this._spritesRenderTime.beginMonitoring();
  80500. });
  80501. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  80502. BABYLON.Tools.EndPerformanceCounter("Sprites");
  80503. _this._spritesRenderTime.endMonitoring(false);
  80504. });
  80505. }
  80506. else {
  80507. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  80508. this._onBeforeSpritesRenderingObserver = null;
  80509. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  80510. this._onAfterSpritesRenderingObserver = null;
  80511. }
  80512. },
  80513. enumerable: true,
  80514. configurable: true
  80515. });
  80516. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  80517. /**
  80518. * Gets the perf counter used for physics time
  80519. */
  80520. get: function () {
  80521. return this._physicsTime;
  80522. },
  80523. enumerable: true,
  80524. configurable: true
  80525. });
  80526. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  80527. /**
  80528. * Gets the physics time capture status
  80529. */
  80530. get: function () {
  80531. return this._capturePhysicsTime;
  80532. },
  80533. /**
  80534. * Enable or disable the physics time capture
  80535. */
  80536. set: function (value) {
  80537. var _this = this;
  80538. if (value === this._capturePhysicsTime) {
  80539. return;
  80540. }
  80541. this._capturePhysicsTime = value;
  80542. if (value) {
  80543. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  80544. BABYLON.Tools.StartPerformanceCounter("Physics");
  80545. _this._physicsTime.beginMonitoring();
  80546. });
  80547. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  80548. BABYLON.Tools.EndPerformanceCounter("Physics");
  80549. _this._physicsTime.endMonitoring();
  80550. });
  80551. }
  80552. else {
  80553. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  80554. this._onBeforePhysicsObserver = null;
  80555. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  80556. this._onAfterPhysicsObserver = null;
  80557. }
  80558. },
  80559. enumerable: true,
  80560. configurable: true
  80561. });
  80562. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  80563. /**
  80564. * Gets the perf counter used for animations time
  80565. */
  80566. get: function () {
  80567. return this._animationsTime;
  80568. },
  80569. enumerable: true,
  80570. configurable: true
  80571. });
  80572. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  80573. /**
  80574. * Gets the animations time capture status
  80575. */
  80576. get: function () {
  80577. return this._captureAnimationsTime;
  80578. },
  80579. /**
  80580. * Enable or disable the animations time capture
  80581. */
  80582. set: function (value) {
  80583. var _this = this;
  80584. if (value === this._captureAnimationsTime) {
  80585. return;
  80586. }
  80587. this._captureAnimationsTime = value;
  80588. if (value) {
  80589. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  80590. _this._animationsTime.endMonitoring();
  80591. });
  80592. }
  80593. else {
  80594. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  80595. this._onAfterAnimationsObserver = null;
  80596. }
  80597. },
  80598. enumerable: true,
  80599. configurable: true
  80600. });
  80601. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  80602. /**
  80603. * Gets the perf counter used for frame time capture
  80604. */
  80605. get: function () {
  80606. return this._frameTime;
  80607. },
  80608. enumerable: true,
  80609. configurable: true
  80610. });
  80611. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  80612. /**
  80613. * Gets the frame time capture status
  80614. */
  80615. get: function () {
  80616. return this._captureFrameTime;
  80617. },
  80618. /**
  80619. * Enable or disable the frame time capture
  80620. */
  80621. set: function (value) {
  80622. this._captureFrameTime = value;
  80623. },
  80624. enumerable: true,
  80625. configurable: true
  80626. });
  80627. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  80628. /**
  80629. * Gets the perf counter used for inter-frames time capture
  80630. */
  80631. get: function () {
  80632. return this._interFrameTime;
  80633. },
  80634. enumerable: true,
  80635. configurable: true
  80636. });
  80637. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  80638. /**
  80639. * Gets the inter-frames time capture status
  80640. */
  80641. get: function () {
  80642. return this._captureInterFrameTime;
  80643. },
  80644. /**
  80645. * Enable or disable the inter-frames time capture
  80646. */
  80647. set: function (value) {
  80648. this._captureInterFrameTime = value;
  80649. },
  80650. enumerable: true,
  80651. configurable: true
  80652. });
  80653. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  80654. /**
  80655. * Gets the perf counter used for render time capture
  80656. */
  80657. get: function () {
  80658. return this._renderTime;
  80659. },
  80660. enumerable: true,
  80661. configurable: true
  80662. });
  80663. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  80664. /**
  80665. * Gets the render time capture status
  80666. */
  80667. get: function () {
  80668. return this._captureRenderTime;
  80669. },
  80670. /**
  80671. * Enable or disable the render time capture
  80672. */
  80673. set: function (value) {
  80674. var _this = this;
  80675. if (value === this._captureRenderTime) {
  80676. return;
  80677. }
  80678. this._captureRenderTime = value;
  80679. if (value) {
  80680. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  80681. _this._renderTime.beginMonitoring();
  80682. BABYLON.Tools.StartPerformanceCounter("Main render");
  80683. });
  80684. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  80685. _this._renderTime.endMonitoring(false);
  80686. BABYLON.Tools.EndPerformanceCounter("Main render");
  80687. });
  80688. }
  80689. else {
  80690. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  80691. this._onBeforeDrawPhaseObserver = null;
  80692. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  80693. this._onAfterDrawPhaseObserver = null;
  80694. }
  80695. },
  80696. enumerable: true,
  80697. configurable: true
  80698. });
  80699. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  80700. /**
  80701. * Gets the perf counter used for draw calls
  80702. */
  80703. get: function () {
  80704. return this.scene.getEngine()._drawCalls;
  80705. },
  80706. enumerable: true,
  80707. configurable: true
  80708. });
  80709. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  80710. /**
  80711. * Gets the perf counter used for texture collisions
  80712. */
  80713. get: function () {
  80714. return this.scene.getEngine()._textureCollisions;
  80715. },
  80716. enumerable: true,
  80717. configurable: true
  80718. });
  80719. SceneInstrumentation.prototype.dispose = function () {
  80720. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  80721. this._onAfterRenderObserver = null;
  80722. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  80723. this._onBeforeActiveMeshesEvaluationObserver = null;
  80724. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  80725. this._onAfterActiveMeshesEvaluationObserver = null;
  80726. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  80727. this._onBeforeRenderTargetsRenderObserver = null;
  80728. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  80729. this._onAfterRenderTargetsRenderObserver = null;
  80730. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  80731. this._onBeforeAnimationsObserver = null;
  80732. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  80733. this._onBeforeParticlesRenderingObserver = null;
  80734. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  80735. this._onAfterParticlesRenderingObserver = null;
  80736. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  80737. this._onBeforeSpritesRenderingObserver = null;
  80738. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  80739. this._onAfterSpritesRenderingObserver = null;
  80740. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  80741. this._onBeforeDrawPhaseObserver = null;
  80742. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  80743. this._onAfterDrawPhaseObserver = null;
  80744. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  80745. this._onBeforePhysicsObserver = null;
  80746. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  80747. this._onAfterPhysicsObserver = null;
  80748. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  80749. this._onAfterAnimationsObserver = null;
  80750. this.scene = null;
  80751. };
  80752. return SceneInstrumentation;
  80753. }());
  80754. BABYLON.SceneInstrumentation = SceneInstrumentation;
  80755. })(BABYLON || (BABYLON = {}));
  80756. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  80757. var BABYLON;
  80758. (function (BABYLON) {
  80759. var _TimeToken = /** @class */ (function () {
  80760. function _TimeToken() {
  80761. this._timeElapsedQueryEnded = false;
  80762. }
  80763. return _TimeToken;
  80764. }());
  80765. BABYLON._TimeToken = _TimeToken;
  80766. })(BABYLON || (BABYLON = {}));
  80767. //# sourceMappingURL=babylon.timeToken.js.map
  80768. var BABYLON;
  80769. (function (BABYLON) {
  80770. /**
  80771. * Background material defines definition.
  80772. */
  80773. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  80774. __extends(BackgroundMaterialDefines, _super);
  80775. /**
  80776. * Constructor of the defines.
  80777. */
  80778. function BackgroundMaterialDefines() {
  80779. var _this = _super.call(this) || this;
  80780. /**
  80781. * True if the diffuse texture is in use.
  80782. */
  80783. _this.DIFFUSE = false;
  80784. /**
  80785. * The direct UV channel to use.
  80786. */
  80787. _this.DIFFUSEDIRECTUV = 0;
  80788. /**
  80789. * True if the diffuse texture is in gamma space.
  80790. */
  80791. _this.GAMMADIFFUSE = false;
  80792. /**
  80793. * True if the diffuse texture has opacity in the alpha channel.
  80794. */
  80795. _this.DIFFUSEHASALPHA = false;
  80796. /**
  80797. * True if you want the material to fade to transparent at grazing angle.
  80798. */
  80799. _this.OPACITYFRESNEL = false;
  80800. /**
  80801. * True if an extra blur needs to be added in the reflection.
  80802. */
  80803. _this.REFLECTIONBLUR = false;
  80804. /**
  80805. * True if you want the material to fade to reflection at grazing angle.
  80806. */
  80807. _this.REFLECTIONFRESNEL = false;
  80808. /**
  80809. * True if you want the material to falloff as far as you move away from the scene center.
  80810. */
  80811. _this.REFLECTIONFALLOFF = false;
  80812. /**
  80813. * False if the current Webgl implementation does not support the texture lod extension.
  80814. */
  80815. _this.TEXTURELODSUPPORT = false;
  80816. /**
  80817. * True to ensure the data are premultiplied.
  80818. */
  80819. _this.PREMULTIPLYALPHA = false;
  80820. /**
  80821. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  80822. */
  80823. _this.USERGBCOLOR = false;
  80824. /**
  80825. * True to add noise in order to reduce the banding effect.
  80826. */
  80827. _this.NOISE = false;
  80828. // Image Processing Configuration.
  80829. _this.IMAGEPROCESSING = false;
  80830. _this.VIGNETTE = false;
  80831. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  80832. _this.VIGNETTEBLENDMODEOPAQUE = false;
  80833. _this.TONEMAPPING = false;
  80834. _this.CONTRAST = false;
  80835. _this.COLORCURVES = false;
  80836. _this.COLORGRADING = false;
  80837. _this.COLORGRADING3D = false;
  80838. _this.SAMPLER3DGREENDEPTH = false;
  80839. _this.SAMPLER3DBGRMAP = false;
  80840. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  80841. _this.EXPOSURE = false;
  80842. // Reflection.
  80843. _this.REFLECTION = false;
  80844. _this.REFLECTIONMAP_3D = false;
  80845. _this.REFLECTIONMAP_SPHERICAL = false;
  80846. _this.REFLECTIONMAP_PLANAR = false;
  80847. _this.REFLECTIONMAP_CUBIC = false;
  80848. _this.REFLECTIONMAP_PROJECTION = false;
  80849. _this.REFLECTIONMAP_SKYBOX = false;
  80850. _this.REFLECTIONMAP_EXPLICIT = false;
  80851. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  80852. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  80853. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  80854. _this.INVERTCUBICMAP = false;
  80855. _this.REFLECTIONMAP_OPPOSITEZ = false;
  80856. _this.LODINREFLECTIONALPHA = false;
  80857. _this.GAMMAREFLECTION = false;
  80858. // Default BJS.
  80859. _this.MAINUV1 = false;
  80860. _this.MAINUV2 = false;
  80861. _this.UV1 = false;
  80862. _this.UV2 = false;
  80863. _this.CLIPPLANE = false;
  80864. _this.POINTSIZE = false;
  80865. _this.FOG = false;
  80866. _this.NORMAL = false;
  80867. _this.NUM_BONE_INFLUENCERS = 0;
  80868. _this.BonesPerMesh = 0;
  80869. _this.INSTANCES = false;
  80870. _this.SHADOWFLOAT = false;
  80871. _this.rebuild();
  80872. return _this;
  80873. }
  80874. return BackgroundMaterialDefines;
  80875. }(BABYLON.MaterialDefines));
  80876. /**
  80877. * Background material used to create an efficient environement around your scene.
  80878. */
  80879. var BackgroundMaterial = /** @class */ (function (_super) {
  80880. __extends(BackgroundMaterial, _super);
  80881. /**
  80882. * constructor
  80883. * @param name The name of the material
  80884. * @param scene The scene to add the material to
  80885. */
  80886. function BackgroundMaterial(name, scene) {
  80887. var _this = _super.call(this, name, scene) || this;
  80888. _this.primaryColor = BABYLON.Color3.White();
  80889. _this.primaryLevel = 1;
  80890. _this.secondaryColor = BABYLON.Color3.Gray();
  80891. _this.secondaryLevel = 1;
  80892. _this.tertiaryColor = BABYLON.Color3.Black();
  80893. _this.tertiaryLevel = 1;
  80894. _this.reflectionTexture = null;
  80895. _this.reflectionBlur = 0;
  80896. _this.diffuseTexture = null;
  80897. /**
  80898. * Specify the list of lights casting shadow on the material.
  80899. * All scene shadow lights will be included if null.
  80900. */
  80901. _this._shadowLights = null;
  80902. _this.shadowLights = null;
  80903. _this.shadowBlurScale = 1;
  80904. _this.shadowLevel = 0;
  80905. _this.sceneCenter = BABYLON.Vector3.Zero();
  80906. _this.opacityFresnel = true;
  80907. _this.reflectionFresnel = false;
  80908. _this.reflectionFalloffDistance = 0.0;
  80909. _this.reflectionAmount = 1.0;
  80910. _this.reflectionReflectance0 = 0.05;
  80911. _this.reflectionReflectance90 = 0.5;
  80912. _this.useRGBColor = true;
  80913. _this.enableNoise = false;
  80914. /**
  80915. * Number of Simultaneous lights allowed on the material.
  80916. */
  80917. _this._maxSimultaneousLights = 4;
  80918. _this.maxSimultaneousLights = 4;
  80919. /**
  80920. * Keep track of the image processing observer to allow dispose and replace.
  80921. */
  80922. _this._imageProcessingObserver = null;
  80923. // Temp values kept as cache in the material.
  80924. _this._renderTargets = new BABYLON.SmartArray(16);
  80925. _this._reflectionControls = BABYLON.Vector4.Zero();
  80926. // Setup the default processing configuration to the scene.
  80927. _this._attachImageProcessingConfiguration(null);
  80928. _this.getRenderTargetTextures = function () {
  80929. _this._renderTargets.reset();
  80930. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  80931. _this._renderTargets.push(_this._diffuseTexture);
  80932. }
  80933. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  80934. _this._renderTargets.push(_this._reflectionTexture);
  80935. }
  80936. return _this._renderTargets;
  80937. };
  80938. return _this;
  80939. }
  80940. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  80941. /**
  80942. * Sets the reflection reflectance fresnel values according to the default standard
  80943. * empirically know to work well :-)
  80944. */
  80945. set: function (value) {
  80946. var reflectionWeight = value;
  80947. if (reflectionWeight < 0.5) {
  80948. reflectionWeight = reflectionWeight * 2.0;
  80949. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  80950. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  80951. }
  80952. else {
  80953. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  80954. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  80955. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  80956. }
  80957. },
  80958. enumerable: true,
  80959. configurable: true
  80960. });
  80961. /**
  80962. * Attaches a new image processing configuration to the PBR Material.
  80963. * @param configuration (if null the scene configuration will be use)
  80964. */
  80965. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  80966. var _this = this;
  80967. if (configuration === this._imageProcessingConfiguration) {
  80968. return;
  80969. }
  80970. // Detaches observer.
  80971. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80972. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80973. }
  80974. // Pick the scene configuration if needed.
  80975. if (!configuration) {
  80976. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  80977. }
  80978. else {
  80979. this._imageProcessingConfiguration = configuration;
  80980. }
  80981. // Attaches observer.
  80982. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  80983. _this._markAllSubMeshesAsImageProcessingDirty();
  80984. });
  80985. };
  80986. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  80987. /**
  80988. * Gets the image processing configuration used either in this material.
  80989. */
  80990. get: function () {
  80991. return this._imageProcessingConfiguration;
  80992. },
  80993. /**
  80994. * Sets the Default image processing configuration used either in the this material.
  80995. *
  80996. * If sets to null, the scene one is in use.
  80997. */
  80998. set: function (value) {
  80999. this._attachImageProcessingConfiguration(value);
  81000. // Ensure the effect will be rebuilt.
  81001. this._markAllSubMeshesAsTexturesDirty();
  81002. },
  81003. enumerable: true,
  81004. configurable: true
  81005. });
  81006. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  81007. /**
  81008. * Gets wether the color curves effect is enabled.
  81009. */
  81010. get: function () {
  81011. return this.imageProcessingConfiguration.colorCurvesEnabled;
  81012. },
  81013. /**
  81014. * Sets wether the color curves effect is enabled.
  81015. */
  81016. set: function (value) {
  81017. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  81018. },
  81019. enumerable: true,
  81020. configurable: true
  81021. });
  81022. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  81023. /**
  81024. * Gets wether the color grading effect is enabled.
  81025. */
  81026. get: function () {
  81027. return this.imageProcessingConfiguration.colorGradingEnabled;
  81028. },
  81029. /**
  81030. * Gets wether the color grading effect is enabled.
  81031. */
  81032. set: function (value) {
  81033. this.imageProcessingConfiguration.colorGradingEnabled = value;
  81034. },
  81035. enumerable: true,
  81036. configurable: true
  81037. });
  81038. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  81039. /**
  81040. * Gets wether tonemapping is enabled or not.
  81041. */
  81042. get: function () {
  81043. return this._imageProcessingConfiguration.toneMappingEnabled;
  81044. },
  81045. /**
  81046. * Sets wether tonemapping is enabled or not
  81047. */
  81048. set: function (value) {
  81049. this._imageProcessingConfiguration.toneMappingEnabled = value;
  81050. },
  81051. enumerable: true,
  81052. configurable: true
  81053. });
  81054. ;
  81055. ;
  81056. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  81057. /**
  81058. * The camera exposure used on this material.
  81059. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  81060. * This corresponds to a photographic exposure.
  81061. */
  81062. get: function () {
  81063. return this._imageProcessingConfiguration.exposure;
  81064. },
  81065. /**
  81066. * The camera exposure used on this material.
  81067. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  81068. * This corresponds to a photographic exposure.
  81069. */
  81070. set: function (value) {
  81071. this._imageProcessingConfiguration.exposure = value;
  81072. },
  81073. enumerable: true,
  81074. configurable: true
  81075. });
  81076. ;
  81077. ;
  81078. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  81079. /**
  81080. * Gets The camera contrast used on this material.
  81081. */
  81082. get: function () {
  81083. return this._imageProcessingConfiguration.contrast;
  81084. },
  81085. /**
  81086. * Sets The camera contrast used on this material.
  81087. */
  81088. set: function (value) {
  81089. this._imageProcessingConfiguration.contrast = value;
  81090. },
  81091. enumerable: true,
  81092. configurable: true
  81093. });
  81094. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  81095. /**
  81096. * Gets the Color Grading 2D Lookup Texture.
  81097. */
  81098. get: function () {
  81099. return this._imageProcessingConfiguration.colorGradingTexture;
  81100. },
  81101. /**
  81102. * Sets the Color Grading 2D Lookup Texture.
  81103. */
  81104. set: function (value) {
  81105. this.imageProcessingConfiguration.colorGradingTexture = value;
  81106. },
  81107. enumerable: true,
  81108. configurable: true
  81109. });
  81110. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  81111. /**
  81112. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  81113. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  81114. * 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;
  81115. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  81116. */
  81117. get: function () {
  81118. return this.imageProcessingConfiguration.colorCurves;
  81119. },
  81120. /**
  81121. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  81122. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  81123. * 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;
  81124. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  81125. */
  81126. set: function (value) {
  81127. this.imageProcessingConfiguration.colorCurves = value;
  81128. },
  81129. enumerable: true,
  81130. configurable: true
  81131. });
  81132. /**
  81133. * The entire material has been created in order to prevent overdraw.
  81134. * @returns false
  81135. */
  81136. BackgroundMaterial.prototype.needAlphaTesting = function () {
  81137. return true;
  81138. };
  81139. /**
  81140. * The entire material has been created in order to prevent overdraw.
  81141. * @returns true if blending is enable
  81142. */
  81143. BackgroundMaterial.prototype.needAlphaBlending = function () {
  81144. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  81145. };
  81146. /**
  81147. * Checks wether the material is ready to be rendered for a given mesh.
  81148. * @param mesh The mesh to render
  81149. * @param subMesh The submesh to check against
  81150. * @param useInstances Specify wether or not the material is used with instances
  81151. */
  81152. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  81153. var _this = this;
  81154. if (useInstances === void 0) { useInstances = false; }
  81155. if (subMesh.effect && this.isFrozen) {
  81156. if (this._wasPreviouslyReady) {
  81157. return true;
  81158. }
  81159. }
  81160. if (!subMesh._materialDefines) {
  81161. subMesh._materialDefines = new BackgroundMaterialDefines();
  81162. }
  81163. var scene = this.getScene();
  81164. var defines = subMesh._materialDefines;
  81165. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  81166. if (defines._renderId === scene.getRenderId()) {
  81167. return true;
  81168. }
  81169. }
  81170. var engine = scene.getEngine();
  81171. // Lights
  81172. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  81173. defines._needNormals = true;
  81174. // Textures
  81175. if (defines._areTexturesDirty) {
  81176. defines._needUVs = false;
  81177. if (scene.texturesEnabled) {
  81178. if (scene.getEngine().getCaps().textureLOD) {
  81179. defines.TEXTURELODSUPPORT = true;
  81180. }
  81181. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  81182. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  81183. return false;
  81184. }
  81185. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  81186. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  81187. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  81188. defines.OPACITYFRESNEL = this._opacityFresnel;
  81189. }
  81190. else {
  81191. defines.DIFFUSE = false;
  81192. defines.DIFFUSEHASALPHA = false;
  81193. defines.GAMMADIFFUSE = false;
  81194. defines.OPACITYFRESNEL = false;
  81195. }
  81196. var reflectionTexture = this._reflectionTexture;
  81197. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  81198. if (!reflectionTexture.isReadyOrNotBlocking()) {
  81199. return false;
  81200. }
  81201. defines.REFLECTION = true;
  81202. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  81203. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  81204. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  81205. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  81206. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  81207. defines.INVERTCUBICMAP = true;
  81208. }
  81209. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  81210. switch (reflectionTexture.coordinatesMode) {
  81211. case BABYLON.Texture.CUBIC_MODE:
  81212. case BABYLON.Texture.INVCUBIC_MODE:
  81213. defines.REFLECTIONMAP_CUBIC = true;
  81214. break;
  81215. case BABYLON.Texture.EXPLICIT_MODE:
  81216. defines.REFLECTIONMAP_EXPLICIT = true;
  81217. break;
  81218. case BABYLON.Texture.PLANAR_MODE:
  81219. defines.REFLECTIONMAP_PLANAR = true;
  81220. break;
  81221. case BABYLON.Texture.PROJECTION_MODE:
  81222. defines.REFLECTIONMAP_PROJECTION = true;
  81223. break;
  81224. case BABYLON.Texture.SKYBOX_MODE:
  81225. defines.REFLECTIONMAP_SKYBOX = true;
  81226. break;
  81227. case BABYLON.Texture.SPHERICAL_MODE:
  81228. defines.REFLECTIONMAP_SPHERICAL = true;
  81229. break;
  81230. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  81231. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  81232. break;
  81233. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  81234. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  81235. break;
  81236. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  81237. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  81238. break;
  81239. }
  81240. if (this.reflectionFresnel) {
  81241. defines.REFLECTIONFRESNEL = true;
  81242. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  81243. this._reflectionControls.x = this.reflectionAmount;
  81244. this._reflectionControls.y = this.reflectionReflectance0;
  81245. this._reflectionControls.z = this.reflectionReflectance90;
  81246. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  81247. }
  81248. else {
  81249. defines.REFLECTIONFRESNEL = false;
  81250. defines.REFLECTIONFALLOFF = false;
  81251. }
  81252. }
  81253. else {
  81254. defines.REFLECTION = false;
  81255. defines.REFLECTIONFALLOFF = false;
  81256. defines.REFLECTIONBLUR = false;
  81257. defines.REFLECTIONMAP_3D = false;
  81258. defines.REFLECTIONMAP_SPHERICAL = false;
  81259. defines.REFLECTIONMAP_PLANAR = false;
  81260. defines.REFLECTIONMAP_CUBIC = false;
  81261. defines.REFLECTIONMAP_PROJECTION = false;
  81262. defines.REFLECTIONMAP_SKYBOX = false;
  81263. defines.REFLECTIONMAP_EXPLICIT = false;
  81264. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  81265. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  81266. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  81267. defines.INVERTCUBICMAP = false;
  81268. defines.REFLECTIONMAP_OPPOSITEZ = false;
  81269. defines.LODINREFLECTIONALPHA = false;
  81270. defines.GAMMAREFLECTION = false;
  81271. }
  81272. }
  81273. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  81274. defines.USERGBCOLOR = this._useRGBColor;
  81275. defines.NOISE = this._enableNoise;
  81276. }
  81277. if (defines._areImageProcessingDirty) {
  81278. if (!this._imageProcessingConfiguration.isReady()) {
  81279. return false;
  81280. }
  81281. this._imageProcessingConfiguration.prepareDefines(defines);
  81282. }
  81283. // Misc.
  81284. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  81285. // Values that need to be evaluated on every frame
  81286. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._shouldTurnAlphaTestOn(mesh));
  81287. // Attribs
  81288. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  81289. if (mesh) {
  81290. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  81291. mesh.createNormals(true);
  81292. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  81293. }
  81294. }
  81295. }
  81296. // Get correct effect
  81297. if (defines.isDirty) {
  81298. defines.markAsProcessed();
  81299. scene.resetCachedMaterial();
  81300. // Fallbacks
  81301. var fallbacks = new BABYLON.EffectFallbacks();
  81302. if (defines.FOG) {
  81303. fallbacks.addFallback(0, "FOG");
  81304. }
  81305. if (defines.POINTSIZE) {
  81306. fallbacks.addFallback(1, "POINTSIZE");
  81307. }
  81308. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  81309. if (defines.NUM_BONE_INFLUENCERS > 0) {
  81310. fallbacks.addCPUSkinningFallback(0, mesh);
  81311. }
  81312. //Attributes
  81313. var attribs = [BABYLON.VertexBuffer.PositionKind];
  81314. if (defines.NORMAL) {
  81315. attribs.push(BABYLON.VertexBuffer.NormalKind);
  81316. }
  81317. if (defines.UV1) {
  81318. attribs.push(BABYLON.VertexBuffer.UVKind);
  81319. }
  81320. if (defines.UV2) {
  81321. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81322. }
  81323. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  81324. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  81325. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  81326. "vFogInfos", "vFogColor", "pointSize",
  81327. "vClipPlane", "mBones",
  81328. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  81329. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  81330. "shadowLevel", "alpha",
  81331. "vBackgroundCenter", "vReflectionControl",
  81332. "vDiffuseInfos", "diffuseMatrix",
  81333. ];
  81334. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  81335. var uniformBuffers = ["Material", "Scene"];
  81336. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  81337. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  81338. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  81339. uniformsNames: uniforms,
  81340. uniformBuffersNames: uniformBuffers,
  81341. samplers: samplers,
  81342. defines: defines,
  81343. maxSimultaneousLights: this._maxSimultaneousLights
  81344. });
  81345. var onCompiled = function (effect) {
  81346. if (_this.onCompiled) {
  81347. _this.onCompiled(effect);
  81348. }
  81349. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  81350. };
  81351. var join = defines.toString();
  81352. subMesh.setEffect(scene.getEngine().createEffect("background", {
  81353. attributes: attribs,
  81354. uniformsNames: uniforms,
  81355. uniformBuffersNames: uniformBuffers,
  81356. samplers: samplers,
  81357. defines: join,
  81358. fallbacks: fallbacks,
  81359. onCompiled: onCompiled,
  81360. onError: this.onError,
  81361. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  81362. }, engine), defines);
  81363. this.buildUniformLayout();
  81364. }
  81365. if (!subMesh.effect || !subMesh.effect.isReady()) {
  81366. return false;
  81367. }
  81368. defines._renderId = scene.getRenderId();
  81369. this._wasPreviouslyReady = true;
  81370. return true;
  81371. };
  81372. /**
  81373. * Build the uniform buffer used in the material.
  81374. */
  81375. BackgroundMaterial.prototype.buildUniformLayout = function () {
  81376. // Order is important !
  81377. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  81378. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  81379. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  81380. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  81381. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  81382. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  81383. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  81384. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  81385. this._uniformBuffer.addUniform("pointSize", 1);
  81386. this._uniformBuffer.addUniform("shadowLevel", 1);
  81387. this._uniformBuffer.addUniform("alpha", 1);
  81388. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  81389. this._uniformBuffer.addUniform("vReflectionControl", 4);
  81390. this._uniformBuffer.create();
  81391. };
  81392. /**
  81393. * Unbind the material.
  81394. */
  81395. BackgroundMaterial.prototype.unbind = function () {
  81396. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  81397. this._uniformBuffer.setTexture("diffuseSampler", null);
  81398. }
  81399. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  81400. this._uniformBuffer.setTexture("reflectionSampler", null);
  81401. }
  81402. _super.prototype.unbind.call(this);
  81403. };
  81404. /**
  81405. * Bind only the world matrix to the material.
  81406. * @param world The world matrix to bind.
  81407. */
  81408. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  81409. this._activeEffect.setMatrix("world", world);
  81410. };
  81411. /**
  81412. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  81413. * @param world The world matrix to bind.
  81414. * @param subMesh The submesh to bind for.
  81415. */
  81416. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  81417. var scene = this.getScene();
  81418. var defines = subMesh._materialDefines;
  81419. if (!defines) {
  81420. return;
  81421. }
  81422. var effect = subMesh.effect;
  81423. if (!effect) {
  81424. return;
  81425. }
  81426. this._activeEffect = effect;
  81427. // Matrices
  81428. this.bindOnlyWorldMatrix(world);
  81429. // Bones
  81430. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  81431. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  81432. if (mustRebind) {
  81433. this._uniformBuffer.bindToEffect(effect, "Material");
  81434. this.bindViewProjection(effect);
  81435. var reflectionTexture = this._reflectionTexture;
  81436. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  81437. // Texture uniforms
  81438. if (scene.texturesEnabled) {
  81439. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  81440. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  81441. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  81442. }
  81443. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  81444. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  81445. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  81446. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  81447. }
  81448. }
  81449. if (this.shadowLevel > 0) {
  81450. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  81451. }
  81452. this._uniformBuffer.updateFloat("alpha", this.alpha);
  81453. // Point size
  81454. if (this.pointsCloud) {
  81455. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  81456. }
  81457. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  81458. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  81459. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  81460. }
  81461. // Textures
  81462. if (scene.texturesEnabled) {
  81463. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  81464. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  81465. }
  81466. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  81467. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  81468. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  81469. }
  81470. else if (!defines.REFLECTIONBLUR) {
  81471. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  81472. }
  81473. else {
  81474. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  81475. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  81476. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  81477. }
  81478. if (defines.REFLECTIONFRESNEL) {
  81479. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  81480. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  81481. }
  81482. }
  81483. }
  81484. // Clip plane
  81485. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  81486. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  81487. }
  81488. if (mustRebind || !this.isFrozen) {
  81489. if (scene.lightsEnabled) {
  81490. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  81491. }
  81492. // View
  81493. this.bindView(effect);
  81494. // Fog
  81495. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  81496. // image processing
  81497. this._imageProcessingConfiguration.bind(this._activeEffect);
  81498. }
  81499. this._uniformBuffer.update();
  81500. this._afterBind(mesh);
  81501. };
  81502. /**
  81503. * Dispose the material.
  81504. * @forceDisposeEffect Force disposal of the associated effect.
  81505. * @forceDisposeTextures Force disposal of the associated textures.
  81506. */
  81507. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  81508. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  81509. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  81510. if (forceDisposeTextures) {
  81511. if (this.diffuseTexture) {
  81512. this.diffuseTexture.dispose();
  81513. }
  81514. if (this.reflectionTexture) {
  81515. this.reflectionTexture.dispose();
  81516. }
  81517. }
  81518. this._renderTargets.dispose();
  81519. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  81520. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  81521. }
  81522. _super.prototype.dispose.call(this, forceDisposeEffect);
  81523. };
  81524. /**
  81525. * Clones the material.
  81526. * @name The cloned name.
  81527. * @returns The cloned material.
  81528. */
  81529. BackgroundMaterial.prototype.clone = function (name) {
  81530. var _this = this;
  81531. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  81532. };
  81533. /**
  81534. * Serializes the current material to its JSON representation.
  81535. * @returns The JSON representation.
  81536. */
  81537. BackgroundMaterial.prototype.serialize = function () {
  81538. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81539. serializationObject.customType = "BABYLON.BackgroundMaterial";
  81540. return serializationObject;
  81541. };
  81542. /**
  81543. * Gets the class name of the material
  81544. * @returns "BackgroundMaterial"
  81545. */
  81546. BackgroundMaterial.prototype.getClassName = function () {
  81547. return "BackgroundMaterial";
  81548. };
  81549. /**
  81550. * Parse a JSON input to create back a background material.
  81551. * @param source
  81552. * @param scene
  81553. * @param rootUrl
  81554. * @returns the instantiated BackgroundMaterial.
  81555. */
  81556. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  81557. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  81558. };
  81559. /**
  81560. * Standard reflectance value at parallel view angle.
  81561. */
  81562. BackgroundMaterial.standardReflectance0 = 0.05;
  81563. /**
  81564. * Standard reflectance value at grazing angle.
  81565. */
  81566. BackgroundMaterial.standardReflectance90 = 0.5;
  81567. __decorate([
  81568. BABYLON.serializeAsColor3()
  81569. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  81570. __decorate([
  81571. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81572. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  81573. __decorate([
  81574. BABYLON.serialize()
  81575. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  81576. __decorate([
  81577. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81578. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  81579. __decorate([
  81580. BABYLON.serializeAsColor3()
  81581. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  81582. __decorate([
  81583. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81584. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  81585. __decorate([
  81586. BABYLON.serialize()
  81587. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  81588. __decorate([
  81589. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81590. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  81591. __decorate([
  81592. BABYLON.serializeAsColor3()
  81593. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  81594. __decorate([
  81595. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81596. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  81597. __decorate([
  81598. BABYLON.serialize()
  81599. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  81600. __decorate([
  81601. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81602. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  81603. __decorate([
  81604. BABYLON.serializeAsTexture()
  81605. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  81606. __decorate([
  81607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81608. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  81609. __decorate([
  81610. BABYLON.serialize()
  81611. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  81612. __decorate([
  81613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81614. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  81615. __decorate([
  81616. BABYLON.serializeAsTexture()
  81617. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  81618. __decorate([
  81619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81620. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  81621. __decorate([
  81622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81623. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  81624. __decorate([
  81625. BABYLON.serialize()
  81626. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  81627. __decorate([
  81628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81629. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  81630. __decorate([
  81631. BABYLON.serialize()
  81632. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  81633. __decorate([
  81634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81635. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  81636. __decorate([
  81637. BABYLON.serializeAsVector3()
  81638. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  81639. __decorate([
  81640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81641. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  81642. __decorate([
  81643. BABYLON.serialize()
  81644. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  81645. __decorate([
  81646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81647. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  81648. __decorate([
  81649. BABYLON.serialize()
  81650. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  81651. __decorate([
  81652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81653. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  81654. __decorate([
  81655. BABYLON.serialize()
  81656. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  81657. __decorate([
  81658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81659. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  81660. __decorate([
  81661. BABYLON.serialize()
  81662. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  81663. __decorate([
  81664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81665. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  81666. __decorate([
  81667. BABYLON.serialize()
  81668. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  81669. __decorate([
  81670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81671. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  81672. __decorate([
  81673. BABYLON.serialize()
  81674. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  81675. __decorate([
  81676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81677. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  81678. __decorate([
  81679. BABYLON.serialize()
  81680. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  81681. __decorate([
  81682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81683. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  81684. __decorate([
  81685. BABYLON.serialize()
  81686. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  81687. __decorate([
  81688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81689. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  81690. __decorate([
  81691. BABYLON.serialize()
  81692. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  81693. __decorate([
  81694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81695. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  81696. __decorate([
  81697. BABYLON.serializeAsImageProcessingConfiguration()
  81698. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  81699. return BackgroundMaterial;
  81700. }(BABYLON.PushMaterial));
  81701. BABYLON.BackgroundMaterial = BackgroundMaterial;
  81702. })(BABYLON || (BABYLON = {}));
  81703. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  81704. var __assign = (this && this.__assign) || Object.assign || function(t) {
  81705. for (var s, i = 1, n = arguments.length; i < n; i++) {
  81706. s = arguments[i];
  81707. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  81708. t[p] = s[p];
  81709. }
  81710. return t;
  81711. };
  81712. var BABYLON;
  81713. (function (BABYLON) {
  81714. /**
  81715. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  81716. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  81717. * It also helps with the default setup of your imageProcessing configuration.
  81718. */
  81719. var EnvironmentHelper = /** @class */ (function () {
  81720. /**
  81721. * constructor
  81722. * @param options
  81723. * @param scene The scene to add the material to
  81724. */
  81725. function EnvironmentHelper(options, scene) {
  81726. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  81727. this._scene = scene;
  81728. this._setupBackground();
  81729. this._setupImageProcessing();
  81730. }
  81731. /**
  81732. * Creates the default options for the helper.
  81733. */
  81734. EnvironmentHelper._getDefaultOptions = function () {
  81735. return {
  81736. createGround: true,
  81737. groundSize: 15,
  81738. groundTexture: this._groundTextureCDNUrl,
  81739. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  81740. groundOpacity: 0.9,
  81741. enableGroundShadow: true,
  81742. groundShadowLevel: 0.5,
  81743. enableGroundMirror: false,
  81744. groundMirrorSizeRatio: 0.3,
  81745. groundMirrorBlurKernel: 64,
  81746. groundMirrorAmount: 1,
  81747. groundMirrorFresnelWeight: 1,
  81748. groundMirrorFallOffDistance: 0,
  81749. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  81750. groundYBias: 0.00001,
  81751. createSkybox: true,
  81752. skyboxSize: 20,
  81753. skyboxTexture: this._skyboxTextureCDNUrl,
  81754. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  81755. backgroundYRotation: 0,
  81756. sizeAuto: true,
  81757. rootPosition: BABYLON.Vector3.Zero(),
  81758. setupImageProcessing: true,
  81759. environmentTexture: this._environmentTextureCDNUrl,
  81760. cameraExposure: 0.8,
  81761. cameraContrast: 1.2,
  81762. toneMappingEnabled: true,
  81763. };
  81764. };
  81765. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  81766. /**
  81767. * Gets the root mesh created by the helper.
  81768. */
  81769. get: function () {
  81770. return this._rootMesh;
  81771. },
  81772. enumerable: true,
  81773. configurable: true
  81774. });
  81775. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  81776. /**
  81777. * Gets the skybox created by the helper.
  81778. */
  81779. get: function () {
  81780. return this._skybox;
  81781. },
  81782. enumerable: true,
  81783. configurable: true
  81784. });
  81785. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  81786. /**
  81787. * Gets the skybox texture created by the helper.
  81788. */
  81789. get: function () {
  81790. return this._skyboxTexture;
  81791. },
  81792. enumerable: true,
  81793. configurable: true
  81794. });
  81795. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  81796. /**
  81797. * Gets the skybox material created by the helper.
  81798. */
  81799. get: function () {
  81800. return this._skyboxMaterial;
  81801. },
  81802. enumerable: true,
  81803. configurable: true
  81804. });
  81805. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  81806. /**
  81807. * Gets the ground mesh created by the helper.
  81808. */
  81809. get: function () {
  81810. return this._ground;
  81811. },
  81812. enumerable: true,
  81813. configurable: true
  81814. });
  81815. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  81816. /**
  81817. * Gets the ground texture created by the helper.
  81818. */
  81819. get: function () {
  81820. return this._groundTexture;
  81821. },
  81822. enumerable: true,
  81823. configurable: true
  81824. });
  81825. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  81826. /**
  81827. * Gets the ground mirror created by the helper.
  81828. */
  81829. get: function () {
  81830. return this._groundMirror;
  81831. },
  81832. enumerable: true,
  81833. configurable: true
  81834. });
  81835. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  81836. /**
  81837. * Gets the ground mirror render list to helps pushing the meshes
  81838. * you wish in the ground reflection.
  81839. */
  81840. get: function () {
  81841. if (this._groundMirror) {
  81842. return this._groundMirror.renderList;
  81843. }
  81844. return null;
  81845. },
  81846. enumerable: true,
  81847. configurable: true
  81848. });
  81849. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  81850. /**
  81851. * Gets the ground material created by the helper.
  81852. */
  81853. get: function () {
  81854. return this._groundMaterial;
  81855. },
  81856. enumerable: true,
  81857. configurable: true
  81858. });
  81859. /**
  81860. * Updates the background according to the new options
  81861. * @param options
  81862. */
  81863. EnvironmentHelper.prototype.updateOptions = function (options) {
  81864. var newOptions = __assign({}, this._options, options);
  81865. if (this._ground && !newOptions.createGround) {
  81866. this._ground.dispose();
  81867. this._ground = null;
  81868. }
  81869. if (this._groundMaterial && !newOptions.createGround) {
  81870. this._groundMaterial.dispose();
  81871. this._groundMaterial = null;
  81872. }
  81873. if (this._groundTexture) {
  81874. if (this._options.groundTexture != newOptions.groundTexture) {
  81875. this._groundTexture.dispose();
  81876. this._groundTexture = null;
  81877. }
  81878. }
  81879. if (this._skybox && !newOptions.createSkybox) {
  81880. this._skybox.dispose();
  81881. this._skybox = null;
  81882. }
  81883. if (this._skyboxMaterial && !newOptions.createSkybox) {
  81884. this._skyboxMaterial.dispose();
  81885. this._skyboxMaterial = null;
  81886. }
  81887. if (this._skyboxTexture) {
  81888. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  81889. this._skyboxTexture.dispose();
  81890. this._skyboxTexture = null;
  81891. }
  81892. }
  81893. if (this._groundMirror && !newOptions.enableGroundMirror) {
  81894. this._groundMirror.dispose();
  81895. this._groundMirror = null;
  81896. }
  81897. if (this._scene.environmentTexture) {
  81898. if (this._options.environmentTexture != newOptions.environmentTexture) {
  81899. this._scene.environmentTexture.dispose();
  81900. }
  81901. }
  81902. this._options = newOptions;
  81903. this._setupBackground();
  81904. this._setupImageProcessing();
  81905. };
  81906. /**
  81907. * Sets the primary color of all the available elements.
  81908. * @param color
  81909. */
  81910. EnvironmentHelper.prototype.setMainColor = function (color) {
  81911. if (this.groundMaterial) {
  81912. this.groundMaterial.primaryColor = color;
  81913. }
  81914. if (this.skyboxMaterial) {
  81915. this.skyboxMaterial.primaryColor = color;
  81916. }
  81917. if (this.groundMirror) {
  81918. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  81919. }
  81920. };
  81921. /**
  81922. * Setup the image processing according to the specified options.
  81923. */
  81924. EnvironmentHelper.prototype._setupImageProcessing = function () {
  81925. if (this._options.setupImageProcessing) {
  81926. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  81927. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  81928. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  81929. this._setupEnvironmentTexture();
  81930. }
  81931. };
  81932. /**
  81933. * Setup the environment texture according to the specified options.
  81934. */
  81935. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  81936. if (this._scene.environmentTexture) {
  81937. return;
  81938. }
  81939. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  81940. this._scene.environmentTexture = this._options.environmentTexture;
  81941. return;
  81942. }
  81943. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  81944. this._scene.environmentTexture = environmentTexture;
  81945. };
  81946. /**
  81947. * Setup the background according to the specified options.
  81948. */
  81949. EnvironmentHelper.prototype._setupBackground = function () {
  81950. if (!this._rootMesh) {
  81951. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  81952. }
  81953. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  81954. var sceneSize = this._getSceneSize();
  81955. if (this._options.createGround) {
  81956. this._setupGround(sceneSize);
  81957. this._setupGroundMaterial();
  81958. this._setupGroundDiffuseTexture();
  81959. if (this._options.enableGroundMirror) {
  81960. this._setupGroundMirrorTexture(sceneSize);
  81961. }
  81962. this._setupMirrorInGroundMaterial();
  81963. }
  81964. if (this._options.createSkybox) {
  81965. this._setupSkybox(sceneSize);
  81966. this._setupSkyboxMaterial();
  81967. this._setupSkyboxReflectionTexture();
  81968. }
  81969. this._rootMesh.position.x = sceneSize.rootPosition.x;
  81970. this._rootMesh.position.z = sceneSize.rootPosition.z;
  81971. this._rootMesh.position.y = sceneSize.rootPosition.y;
  81972. };
  81973. /**
  81974. * Get the scene sizes according to the setup.
  81975. */
  81976. EnvironmentHelper.prototype._getSceneSize = function () {
  81977. var groundSize = this._options.groundSize;
  81978. var skyboxSize = this._options.skyboxSize;
  81979. var rootPosition = this._options.rootPosition;
  81980. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  81981. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  81982. }
  81983. var sceneExtends = this._scene.getWorldExtends();
  81984. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  81985. if (this._options.sizeAuto) {
  81986. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  81987. this._scene.activeCamera.upperRadiusLimit) {
  81988. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  81989. skyboxSize = groundSize;
  81990. }
  81991. var sceneDiagonalLenght = sceneDiagonal.length();
  81992. if (sceneDiagonalLenght > groundSize) {
  81993. groundSize = sceneDiagonalLenght * 2;
  81994. skyboxSize = groundSize;
  81995. }
  81996. // 10 % bigger.
  81997. groundSize *= 1.1;
  81998. skyboxSize *= 1.5;
  81999. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  82000. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  82001. }
  82002. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  82003. };
  82004. /**
  82005. * Setup the ground according to the specified options.
  82006. */
  82007. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  82008. var _this = this;
  82009. if (!this._ground) {
  82010. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  82011. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  82012. this._ground.parent = this._rootMesh;
  82013. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  82014. }
  82015. this._ground.receiveShadows = this._options.enableGroundShadow;
  82016. };
  82017. /**
  82018. * Setup the ground material according to the specified options.
  82019. */
  82020. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  82021. if (!this._groundMaterial) {
  82022. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  82023. }
  82024. this._groundMaterial.alpha = this._options.groundOpacity;
  82025. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  82026. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  82027. this._groundMaterial.primaryLevel = 1;
  82028. this._groundMaterial.primaryColor = this._options.groundColor;
  82029. this._groundMaterial.secondaryLevel = 0;
  82030. this._groundMaterial.tertiaryLevel = 0;
  82031. this._groundMaterial.useRGBColor = false;
  82032. this._groundMaterial.enableNoise = true;
  82033. if (this._ground) {
  82034. this._ground.material = this._groundMaterial;
  82035. }
  82036. };
  82037. /**
  82038. * Setup the ground diffuse texture according to the specified options.
  82039. */
  82040. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  82041. if (!this._groundMaterial) {
  82042. return;
  82043. }
  82044. if (this._groundTexture) {
  82045. return;
  82046. }
  82047. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  82048. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  82049. return;
  82050. }
  82051. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  82052. diffuseTexture.gammaSpace = false;
  82053. diffuseTexture.hasAlpha = true;
  82054. this._groundMaterial.diffuseTexture = diffuseTexture;
  82055. };
  82056. /**
  82057. * Setup the ground mirror texture according to the specified options.
  82058. */
  82059. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  82060. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82061. if (!this._groundMirror) {
  82062. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  82063. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  82064. this._groundMirror.anisotropicFilteringLevel = 1;
  82065. this._groundMirror.wrapU = wrapping;
  82066. this._groundMirror.wrapV = wrapping;
  82067. this._groundMirror.gammaSpace = false;
  82068. if (this._groundMirror.renderList) {
  82069. for (var i = 0; i < this._scene.meshes.length; i++) {
  82070. var mesh = this._scene.meshes[i];
  82071. if (mesh !== this._ground &&
  82072. mesh !== this._skybox &&
  82073. mesh !== this._rootMesh) {
  82074. this._groundMirror.renderList.push(mesh);
  82075. }
  82076. }
  82077. }
  82078. }
  82079. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  82080. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  82081. };
  82082. /**
  82083. * Setup the ground to receive the mirror texture.
  82084. */
  82085. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  82086. if (this._groundMaterial) {
  82087. this._groundMaterial.reflectionTexture = this._groundMirror;
  82088. this._groundMaterial.reflectionFresnel = true;
  82089. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  82090. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  82091. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  82092. }
  82093. };
  82094. /**
  82095. * Setup the skybox according to the specified options.
  82096. */
  82097. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  82098. var _this = this;
  82099. if (!this._skybox) {
  82100. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  82101. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  82102. }
  82103. this._skybox.parent = this._rootMesh;
  82104. };
  82105. /**
  82106. * Setup the skybox material according to the specified options.
  82107. */
  82108. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  82109. if (!this._skybox) {
  82110. return;
  82111. }
  82112. if (!this._skyboxMaterial) {
  82113. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  82114. }
  82115. this._skyboxMaterial.useRGBColor = false;
  82116. this._skyboxMaterial.primaryLevel = 1;
  82117. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  82118. this._skyboxMaterial.secondaryLevel = 0;
  82119. this._skyboxMaterial.tertiaryLevel = 0;
  82120. this._skyboxMaterial.enableNoise = true;
  82121. this._skybox.material = this._skyboxMaterial;
  82122. };
  82123. /**
  82124. * Setup the skybox reflection texture according to the specified options.
  82125. */
  82126. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  82127. if (!this._skyboxMaterial) {
  82128. return;
  82129. }
  82130. if (this._skyboxTexture) {
  82131. return;
  82132. }
  82133. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  82134. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  82135. return;
  82136. }
  82137. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  82138. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  82139. this._skyboxTexture.gammaSpace = false;
  82140. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  82141. };
  82142. /**
  82143. * Dispose all the elements created by the Helper.
  82144. */
  82145. EnvironmentHelper.prototype.dispose = function () {
  82146. if (this._groundMaterial) {
  82147. this._groundMaterial.dispose(true, true);
  82148. }
  82149. if (this._skyboxMaterial) {
  82150. this._skyboxMaterial.dispose(true, true);
  82151. }
  82152. this._rootMesh.dispose(false);
  82153. };
  82154. /**
  82155. * Default ground texture URL.
  82156. */
  82157. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  82158. /**
  82159. * Default skybox texture URL.
  82160. */
  82161. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  82162. /**
  82163. * Default environment texture URL.
  82164. */
  82165. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  82166. return EnvironmentHelper;
  82167. }());
  82168. BABYLON.EnvironmentHelper = EnvironmentHelper;
  82169. })(BABYLON || (BABYLON = {}));
  82170. //# sourceMappingURL=babylon.environmentHelper.js.map
  82171. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\nvoid main() {\ngl_PointSize=1.0;\ngl_Position=vec4(position,1.0);\n}","gpuRenderParticlesPixelShader":"void main() {\ngl_FragColor=vec4(1.0);\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\nuniform float timeDelta;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec3 outVelocity;\nvoid main() {\nif (age>=life) {\n\noutPosition=vec3(0,0,0);\n\noutAge=0.0;\noutLife=life;\n\noutVelocity=vec3(0,1,0);\n} else {\noutPosition=position+velocity*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutVelocity=velocity;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\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}"};
  82172. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  82173. (function universalModuleDefinition(root, factory) {
  82174. var f = factory();
  82175. if (root && root["BABYLON"]) {
  82176. return;
  82177. }
  82178. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  82179. globalObject["BABYLON"] = f;
  82180. if(typeof exports === 'object' && typeof module === 'object')
  82181. module.exports = f;
  82182. else if(typeof define === 'function' && define.amd)
  82183. define(["BABYLON"], factory);
  82184. else if(typeof exports === 'object')
  82185. exports["BABYLON"] = f;
  82186. else {
  82187. root["BABYLON"] = f;
  82188. }
  82189. })(this, function() {
  82190. return BABYLON;
  82191. });